TypeScript 5.8装饰器中间件:从元编程到AOP架构的6种生产模式

编程语言

TypeScript装饰器终于可以上生产了

你还在用experimentalDecoratorsemitDecoratorMetadata的Legacy装饰器?每次TypeScript升级都提心吊胆怕break?2026年,TC39装饰器规范已经进入Stage 3.7,TypeScript 5.8原生支持标准装饰器——不再需要实验性标志,不再有语义歧义,装饰器中间件终于可以放心上生产。从方法拦截器到AOP架构,从参数验证到依赖注入,装饰器正在重新定义TypeScript的元编程范式。

本文将从TC39装饰器核心概念出发,带你完成方法拦截器与日志装饰器→类转换器与元数据注册→参数验证装饰器→AOP中间件链→依赖注入容器→装饰器组合与管道模式的6种生产模式,从规范到落地,一步不落。


核心要点

  • TC39标准装饰器与Legacy装饰器的本质区别:不修改被装饰对象,而是替换/包装
  • 装饰器中间件的3层架构:定义层(Decorator)→ 注册层(Metadata)→ 执行层(Middleware Chain)
  • 6种生产模式覆盖日志、验证、AOP、DI、管道组合等核心场景
  • 5个常见坑及解决方案,10个常见报错排查
  • 完整对比:TC39装饰器 vs Legacy装饰器 vs 装饰器工厂

目录

  • TC39装饰器核心概念
  • 模式1:方法拦截器与日志装饰器
  • 模式2:类转换器与元数据注册
  • 模式3:参数验证装饰器
  • 模式4:AOP中间件链
  • 模式5:依赖注入容器
  • 模式6:装饰器组合与管道模式
  • 5个常见坑及解决方案
  • 10个常见报错排查
  • 进阶优化技巧
  • 对比分析:TC39装饰器 vs Legacy装饰器 vs 装饰器工厂
  • 在线工具推荐
  • 总结

TC39装饰器核心概念

概念 说明
TC39 Decorator ECMAScript标准装饰器提案,Stage 3.7,TypeScript 5.8原生支持
Method Decorator 方法装饰器,拦截方法调用,可修改参数/返回值/异常
Class Decorator 类装饰器,替换或增强类定义,可注入元数据
Accessor Decorator getter/setter装饰器,拦截属性访问
Field Decorator 字段装饰器,初始化时触发,可替换初始值
Decorator Context 装饰器上下文对象,提供kind、name、access等元信息
Add Initializer 在类实例化时自动执行的初始化钩子
Metadata 通过Symbol附加到类/方法上的元数据,用于DI、验证等

TC39装饰器执行流程

定义阶段:
  @log                           装饰器工厂调用
  @validate                      返回装饰器函数
  class UserService {            装饰器按从下到上顺序执行
    @cache                       方法装饰器先执行
    async getUser(id: string) {  类装饰器最后执行
      ...
    }
  }

运行阶段:
  const instance = new UserService()  → 触发 addInitializer 钩子
  instance.getUser('123')             → 触发方法装饰器的包装逻辑

装饰器上下文(DecoratorContext):
  {
    kind: 'method' | 'class' | 'accessor' | 'field',
    name: 'getUser' | 'UserService',
    access: { get, set, has },
    addInitializer(fn) → 注册初始化钩子,
    static: boolean,
    private: boolean
  }

TC39 vs Legacy装饰器核心区别

Legacy装饰器(experimentalDecorators):
  @log                              修改原始描述符
  class Svc {                       顺序:从上到下
    descriptor.value = wrappedFn    直接修改被装饰对象
  }

TC39标准装饰器:
  @log                              返回替换值
  class Svc {                       顺序:从下到上
    return { ...descriptor,         不修改原始对象,返回新的
      method: wrappedFn }           函数式、不可变
  }

模式1:方法拦截器与日志装饰器

方法拦截器是装饰器中间件最基础的模式——在不修改原始方法代码的前提下,拦截方法调用,添加日志、计时、重试等横切逻辑。

基础日志装饰器

type DecoratorTarget = {
  [key: string]: (...args: any[]) => any;
};

function log(
  target: DecoratorTarget,
  context: ClassMethodDecoratorContext
) {
  const methodName = String(context.name);

  function replacementMethod(this: DecoratorTarget, ...args: any[]) {
    const startTime = performance.now();
    const className = this.constructor.name;

    console.log(`[${className}.${methodName}] 调用开始`, {
      args: args.length > 0 ? args : undefined,
      timestamp: new Date().toISOString(),
    });

    try {
      const result = target.value.apply(this, args);

      if (result instanceof Promise) {
        return result.then(
          (resolvedValue) => {
            const duration = performance.now() - startTime;
            console.log(`[${className}.${methodName}] 调用成功`, {
              duration: `${duration.toFixed(2)}ms`,
              hasResult: resolvedValue !== undefined,
            });
            return resolvedValue;
          },
          (error) => {
            const duration = performance.now() - startTime;
            console.error(`[${className}.${methodName}] 异步调用失败`, {
              duration: `${duration.toFixed(2)}ms`,
              error: error instanceof Error ? error.message : String(error),
            });
            throw error;
          }
        );
      }

      const duration = performance.now() - startTime;
      console.log(`[${className}.${methodName}] 调用成功`, {
        duration: `${duration.toFixed(2)}ms`,
      });
      return result;
    } catch (error) {
      const duration = performance.now() - startTime;
      console.error(`[${className}.${methodName}] 同步调用失败`, {
        duration: `${duration.toFixed(2)}ms`,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  return replacementMethod;
}

可配置日志装饰器工厂

interface LogOptions {
  level?: 'debug' | 'info' | 'warn' | 'error';
  includeArgs?: boolean;
  includeResult?: boolean;
  maxArgLength?: number;
  slowThreshold?: number;
}

function createLogDecorator(options: LogOptions = {}) {
  const {
    level = 'info',
    includeArgs = true,
    includeResult = false,
    maxArgLength = 200,
    slowThreshold = 1000,
  } = options;

  const levelPriority = { debug: 0, info: 1, warn: 2, error: 3 };

  return function logDecorator(
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const methodName = String(context.name);

    function replacementMethod(this: DecoratorTarget, ...args: any[]) {
      const startTime = performance.now();
      const className = this.constructor.name;
      const logData: Record<string, unknown> = {
        method: `${className}.${methodName}`,
        timestamp: new Date().toISOString(),
      };

      if (includeArgs && args.length > 0) {
        const serializedArgs = JSON.stringify(args);
        logData.args = serializedArgs.length > maxArgLength
          ? serializedArgs.slice(0, maxArgLength) + '...'
          : args;
      }

      const logFn = console[level] || console.info;
      logFn(`[LOG] ${logData.method} 调用`, logData);

      try {
        const result = target.value.apply(this, args);

        if (result instanceof Promise) {
          return result.then(
            (resolvedValue) => {
              const duration = performance.now() - startTime;
              const resultLogData: Record<string, unknown> = {
                method: `${className}.${methodName}`,
                duration: `${duration.toFixed(2)}ms`,
              };
              if (includeResult) {
                resultLogData.result = resolvedValue;
              }
              if (duration > slowThreshold) {
                console.warn(
                  `[SLOW] ${className}.${methodName} 耗时 ${duration.toFixed(2)}ms`,
                  resultLogData
                );
              } else {
                logFn(`[LOG] ${className}.${methodName} 完成`, resultLogData);
              }
              return resolvedValue;
            },
            (error) => {
              const duration = performance.now() - startTime;
              console.error(`[ERROR] ${className}.${methodName} 异步失败`, {
                duration: `${duration.toFixed(2)}ms`,
                error: error instanceof Error ? error.message : String(error),
              });
              throw error;
            }
          );
        }

        const duration = performance.now() - startTime;
        const resultLogData: Record<string, unknown> = {
          method: `${className}.${methodName}`,
          duration: `${duration.toFixed(2)}ms`,
        };
        if (includeResult) {
          resultLogData.result = result;
        }
        logFn(`[LOG] ${className}.${methodName} 完成`, resultLogData);
        return result;
      } catch (error) {
        const duration = performance.now() - startTime;
        console.error(`[ERROR] ${className}.${methodName} 同步失败`, {
          duration: `${duration.toFixed(2)}ms`,
          error: error instanceof Error ? error.message : String(error),
        });
        throw error;
      }
    }

    return replacementMethod;
  };
}

const logVerbose = createLogDecorator({
  level: 'debug',
  includeArgs: true,
  includeResult: true,
  slowThreshold: 500,
});

const logMinimal = createLogDecorator({
  level: 'info',
  includeArgs: false,
  includeResult: false,
  slowThreshold: 2000,
});

使用示例

class PaymentService {
  @logVerbose
  async processPayment(orderId: string, amount: number): Promise<string> {
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (amount <= 0) {
      throw new Error('金额必须大于0');
    }
    return `PAY-${orderId}-${Date.now()}`;
  }

  @logMinimal
  getPaymentStatus(paymentId: string): string {
    return 'completed';
  }
}

const paymentService = new PaymentService();
await paymentService.processPayment('ORD-001', 99.99);

模式2:类转换器与元数据注册

类装饰器可以替换整个类定义,也可以通过addInitializer在实例化时注入元数据。这是实现依赖注入、路由注册、ORM映射的基础。

类装饰器基础:注册路由元数据

const ROUTE_METADATA_KEY = Symbol('route-metadata');
const CONTROLLER_METADATA_KEY = Symbol('controller-metadata');

interface RouteMetadata {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  path: string;
  handlerName: string;
}

interface ControllerMetadata {
  basePath: string;
  routes: RouteMetadata[];
}

function Controller(basePath: string) {
  return function <T extends { new (...args: any[]): any }>(
    target: T,
    context: ClassDecoratorContext
  ) {
    const routes: RouteMetadata[] = Reflect.getMetadata(
      ROUTE_METADATA_KEY,
      target.prototype
    ) || [];

    const metadata: ControllerMetadata = {
      basePath,
      routes,
    };

    Reflect.defineMetadata(
      CONTROLLER_METADATA_KEY,
      metadata,
      target
    );

    return class extends target {
      constructor(...args: any[]) {
        super(...args);
        console.log(`[Controller] ${basePath} 已注册,包含 ${routes.length} 个路由`);
      }
    };
  };
}

function Route(method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const handlerName = String(context.name);
    const existingRoutes: RouteMetadata[] = Reflect.getMetadata(
      ROUTE_METADATA_KEY,
      context.static ? target : target
    ) || [];

    existingRoutes.push({ method, path, handlerName });

    Reflect.defineMetadata(
      ROUTE_METADATA_KEY,
      existingRoutes,
      context.static ? target : target
    );

    return target.value;
  };
}

元数据注册与查询

const VALIDATION_METADATA_KEY = Symbol('validation-metadata');
const FIELD_METADATA_KEY = Symbol('field-metadata');

interface FieldMetadata {
  fieldName: string;
  type: string;
  required: boolean;
  validator?: (value: any) => boolean;
  errorMessage?: string;
}

interface ValidationMetadata {
  fields: FieldMetadata[];
  schemaName: string;
}

function Field(options: Omit<FieldMetadata, 'fieldName'> = {}) {
  return function (
    target: ClassAccessorDecoratorTarget<any, any>,
    context: ClassAccessorDecoratorContext
  ) {
    const fieldName = String(context.name);
    const fieldMeta: FieldMetadata = {
      fieldName,
      type: options.type || 'string',
      required: options.required ?? true,
      validator: options.validator,
      errorMessage: options.errorMessage,
    };

    context.addInitializer(function (this: any) {
      const existingFields: FieldMetadata[] = Reflect.getMetadata(
        FIELD_METADATA_KEY,
        this.constructor
      ) || [];
      existingFields.push(fieldMeta);
      Reflect.defineMetadata(FIELD_METADATA_KEY, existingFields, this.constructor);
    });

    return {
      get(this: any) {
        return target.get.call(this);
      },
      set(this: any, value: any) {
        if (fieldMeta.required && (value === null || value === undefined)) {
          throw new Error(`${fieldName} 是必填字段`);
        }
        if (fieldMeta.validator && !fieldMeta.validator(value)) {
          throw new Error(fieldMeta.errorMessage || `${fieldName} 校验失败`);
        }
        target.set.call(this, value);
      },
    };
  };
}

function Validatable(schemaName: string) {
  return function <T extends { new (...args: any[]): any }>(
    target: T,
    context: ClassDecoratorContext
  ) {
    return class extends target {
      constructor(...args: any[]) {
        super(...args);
        const fields: FieldMetadata[] = Reflect.getMetadata(
          FIELD_METADATA_KEY,
          this.constructor
        ) || [];
        const metadata: ValidationMetadata = { fields, schemaName };
        Reflect.defineMetadata(VALIDATION_METADATA_KEY, metadata, this.constructor);
      }

      static getValidationSchema(): ValidationMetadata {
        const fields: FieldMetadata[] = Reflect.getMetadata(
          FIELD_METADATA_KEY,
          this
        ) || [];
        return { fields, schemaName };
      }

      validate(): { valid: boolean; errors: string[] } {
        const errors: string[] = [];
        const fields: FieldMetadata[] = Reflect.getMetadata(
          FIELD_METADATA_KEY,
          this.constructor
        ) || [];
        for (const field of fields) {
          const value = (this as any)[field.fieldName];
          if (field.required && (value === null || value === undefined)) {
            errors.push(`${field.fieldName} 是必填字段`);
          }
          if (field.validator && !field.validator(value)) {
            errors.push(field.errorMessage || `${field.fieldName} 校验失败`);
          }
        }
        return { valid: errors.length === 0, errors };
      }
    };
  };
}

使用示例

@Validatable('User')
class User {
  @Field({ type: 'string', required: true })
  accessor name: string = '';

  @Field({
    type: 'string',
    required: true,
    validator: (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
    errorMessage: '邮箱格式不正确',
  })
  accessor email: string = '';

  @Field({ type: 'number', required: false })
  accessor age: number = 0;
}

const user = new User();
user.name = '张三';
user.email = 'zhang@example.com';
user.age = 28;

const result = user.validate();
console.log(result);

const schema = User.getValidationSchema();
console.log(schema);

模式3:参数验证装饰器

参数验证是装饰器中间件最实用的场景之一——在方法执行前自动校验参数类型和约束,避免运行时类型错误。

类型校验装饰器

interface ValidationRule {
  type: 'string' | 'number' | 'boolean' | 'object' | 'array';
  required?: boolean;
  minLength?: number;
  maxLength?: number;
  min?: number;
  max?: number;
  pattern?: RegExp;
  custom?: (value: any) => boolean;
  message?: string;
}

function validateParams(...rules: ValidationRule[]) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const methodName = String(context.name);

    function replacementMethod(this: DecoratorTarget, ...args: any[]) {
      for (let i = 0; i < rules.length; i++) {
        const rule = rules[i];
        const value = args[i];
        const paramName = `参数${i + 1}`;

        if (rule.required && (value === null || value === undefined)) {
          throw new TypeError(
            `[${this.constructor.name}.${methodName}] ${paramName} 是必填项`
          );
        }

        if (value !== null && value !== undefined) {
          const actualType = Array.isArray(value) ? 'array' : typeof value;
          if (actualType !== rule.type) {
            throw new TypeError(
              `[${this.constructor.name}.${methodName}] ${paramName} 类型错误:期望 ${rule.type},实际 ${actualType}`
            );
          }

          if (rule.type === 'string') {
            if (rule.minLength && value.length < rule.minLength) {
              throw new RangeError(
                `[${this.constructor.name}.${methodName}] ${paramName} 最小长度 ${rule.minLength}`
              );
            }
            if (rule.maxLength && value.length > rule.maxLength) {
              throw new RangeError(
                `[${this.constructor.name}.${methodName}] ${paramName} 最大长度 ${rule.maxLength}`
              );
            }
            if (rule.pattern && !rule.pattern.test(value)) {
              throw new Error(
                rule.message || `[${this.constructor.name}.${methodName}] ${paramName} 格式不正确`
              );
            }
          }

          if (rule.type === 'number') {
            if (rule.min !== undefined && value < rule.min) {
              throw new RangeError(
                `[${this.constructor.name}.${methodName}] ${paramName} 最小值 ${rule.min}`
              );
            }
            if (rule.max !== undefined && value > rule.max) {
              throw new RangeError(
                `[${this.constructor.name}.${methodName}] ${paramName} 最大值 ${rule.max}`
              );
            }
          }

          if (rule.custom && !rule.custom(value)) {
            throw new Error(
              rule.message || `[${this.constructor.name}.${methodName}] ${paramName} 校验失败`
            );
          }
        }
      }

      return target.value.apply(this, args);
    }

    return replacementMethod;
  };
}

Schema验证装饰器(集成Zod)

import { z, ZodSchema } from 'zod';

function validateWithSchema(schemas: ZodSchema[]) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const methodName = String(context.name);

    function replacementMethod(this: DecoratorTarget, ...args: any[]) {
      for (let i = 0; i < schemas.length; i++) {
        if (i >= args.length) continue;

        const result = schemas[i].safeParse(args[i]);
        if (!result.success) {
          const errors = result.error.issues.map(
            (issue) => `${issue.path.join('.')}: ${issue.message}`
          );
          throw new Error(
            `[${this.constructor.name}.${methodName}] 参数${i + 1}校验失败: ${errors.join('; ')}`
          );
        }

        args[i] = result.data;
      }

      return target.value.apply(this, args);
    }

    return replacementMethod;
  };
}

使用示例

const OrderIdSchema = z.string().uuid();
const CreateOrderSchema = z.object({
  productId: z.string().min(1),
  quantity: z.number().int().min(1).max(999),
  price: z.number().positive(),
  address: z.object({
    city: z.string().min(1),
    street: z.string().min(1),
    zipCode: z.string().regex(/^\d{6}$/),
  }),
});

class OrderService {
  @validateParams(
    { type: 'string', required: true, pattern: /^[A-Z]{2}-\d{4}$/, message: '订单号格式:XX-0000' },
    { type: 'number', required: true, min: 0, max: 1000000 }
  )
  createOrder(orderId: string, amount: number): string {
    return `订单 ${orderId} 已创建,金额 ${amount}`;
  }

  @validateWithSchema([OrderIdSchema, CreateOrderSchema])
  async processOrder(orderId: string, orderData: z.infer<typeof CreateOrderSchema>) {
    return { orderId, status: 'processed', ...orderData };
  }
}

const orderService = new OrderService();
orderService.createOrder('CN-1234', 99.99);

try {
  orderService.createOrder('invalid', -1);
} catch (error) {
  console.error(error);
}

模式4:AOP中间件链

AOP(面向切面编程)是装饰器中间件最强大的应用——将日志、缓存、权限、重试等横切关注点从业务逻辑中解耦,通过中间件链组合执行。

中间件核心架构

请求流入
   │
   ▼
┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
│  Auth    │───▶│  Cache   │───▶│  Retry   │───▶│  Log     │
│ 中间件   │    │ 中间件    │    │ 中间件    │    │ 中间件    │
└──────────┘    └──────────┘    └──────────┘    └──────────┘
                                                   │
                                                   ▼
                                            ┌──────────┐
                                            │ 业务方法  │
                                            │ getUser() │
                                            └──────────┘
                                                   │
                                                   ▼
                                              返回结果

中间件接口定义

interface MiddlewareContext {
  className: string;
  methodName: string;
  args: any[];
  result?: any;
  error?: Error;
  metadata: Map<string, any>;
  startTime: number;
}

type NextFunction = () => Promise<any>;

interface Middleware {
  name: string;
  execute(context: MiddlewareContext, next: NextFunction): Promise<any>;
}

class MiddlewareChain {
  private middlewares: Middleware[] = [];

  use(middleware: Middleware): this {
    this.middlewares.push(middleware);
    return this;
  }

  async execute(
    className: string,
    methodName: string,
    args: any[],
    target: (...args: any[]) => any,
    thisArg: any
  ): Promise<any> {
    const context: MiddlewareContext = {
      className,
      methodName,
      args,
      metadata: new Map(),
      startTime: performance.now(),
    };

    let index = 0;

    const dispatch = async (): Promise<any> => {
      if (index >= this.middlewares.length) {
        context.result = await target.apply(thisArg, args);
        return context.result;
      }

      const middleware = this.middlewares[index++];
      return middleware.execute(context, dispatch);
    };

    return dispatch();
  }
}

内置中间件实现

class AuthMiddleware implements Middleware {
  name = 'auth';

  constructor(private permissionChecker: (method: string) => boolean) {}

  async execute(context: MiddlewareContext, next: NextFunction): Promise<any> {
    const hasPermission = this.permissionChecker(context.methodName);
    if (!hasPermission) {
      throw new Error(`[${context.className}.${context.methodName}] 权限不足`);
    }
    context.metadata.set('auth.checked', true);
    return next();
  }
}

class CacheMiddleware implements Middleware {
  name = 'cache';

  private cache = new Map<string, { value: any; expireAt: number }>();

  constructor(private ttl: number = 60000) {}

  async execute(context: MiddlewareContext, next: NextFunction): Promise<any> {
    const cacheKey = `${context.className}:${context.methodName}:${JSON.stringify(context.args)}`;
    const cached = this.cache.get(cacheKey);

    if (cached && cached.expireAt > Date.now()) {
      context.metadata.set('cache.hit', true);
      return cached.value;
    }

    context.metadata.set('cache.hit', false);
    const result = await next();

    this.cache.set(cacheKey, {
      value: result,
      expireAt: Date.now() + this.ttl,
    });

    return result;
  }

  invalidate(pattern?: string): void {
    if (!pattern) {
      this.cache.clear();
      return;
    }
    for (const key of this.cache.keys()) {
      if (key.includes(pattern)) {
        this.cache.delete(key);
      }
    }
  }
}

class RetryMiddleware implements Middleware {
  name = 'retry';

  constructor(
    private maxRetries: number = 3,
    private delayMs: number = 1000,
    private retryOn: (error: Error) => boolean = () => true
  ) {}

  async execute(context: MiddlewareContext, next: NextFunction): Promise<any> {
    let lastError: Error | undefined;

    for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
      try {
        const result = await next();
        if (attempt > 1) {
          context.metadata.set('retry.attempts', attempt);
        }
        return result;
      } catch (error) {
        lastError = error instanceof Error ? error : new Error(String(error));

        if (attempt < this.maxRetries && this.retryOn(lastError)) {
          const delay = this.delayMs * Math.pow(2, attempt - 1);
          await new Promise((resolve) => setTimeout(resolve, delay));
          continue;
        }

        throw lastError;
      }
    }

    throw lastError!;
  }
}

class LoggingMiddleware implements Middleware {
  name = 'logging';

  async execute(context: MiddlewareContext, next: NextFunction): Promise<any> {
    const startTime = performance.now();
    const logPrefix = `[${context.className}.${context.methodName}]`;

    console.log(`${logPrefix} 调用开始`, {
      args: context.args,
      timestamp: new Date().toISOString(),
    });

    try {
      const result = await next();
      const duration = performance.now() - startTime;
      console.log(`${logPrefix} 调用成功`, {
        duration: `${duration.toFixed(2)}ms`,
        cacheHit: context.metadata.get('cache.hit'),
      });
      return result;
    } catch (error) {
      const duration = performance.now() - startTime;
      console.error(`${logPrefix} 调用失败`, {
        duration: `${duration.toFixed(2)}ms`,
        error: error instanceof Error ? error.message : String(error),
        retryAttempts: context.metadata.get('retry.attempts'),
      });
      throw error;
    }
  }
}

AOP装饰器

const globalMiddlewareChain = new MiddlewareChain();

globalMiddlewareChain
  .use(new AuthMiddleware((method) => true))
  .use(new CacheMiddleware(30000))
  .use(new RetryMiddleware(3, 1000))
  .use(new LoggingMiddleware());

function UseMiddleware(chain?: MiddlewareChain) {
  const middlewareChain = chain || globalMiddlewareChain;

  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const originalMethod = target.value;
    const methodName = String(context.name);

    async function replacementMethod(this: any, ...args: any[]) {
      return middlewareChain.execute(
        this.constructor.name,
        methodName,
        args,
        originalMethod,
        this
      );
    }

    return replacementMethod;
  };
}

class UserService {
  @UseMiddleware()
  async getUser(id: string): Promise<{ id: string; name: string }> {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error(`获取用户失败: ${response.status}`);
    return response.json();
  }

  @UseMiddleware()
  async createUser(data: { name: string; email: string }): Promise<string> {
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error(`创建用户失败: ${response.status}`);
    return response.json();
  }
}

模式5:依赖注入容器

依赖注入(DI)是装饰器中间件在企业级应用中最核心的模式——通过装饰器声明依赖关系,容器自动解析和注入实例。

DI容器实现

const INJECT_METADATA_KEY = Symbol('inject');
const INJECTABLE_METADATA_KEY = Symbol('injectable');
const SCOPE_METADATA_KEY = Symbol('scope');

enum InjectionScope {
  Singleton = 'singleton',
  Transient = 'transient',
  Request = 'request',
}

interface InjectionToken<T = any> {
  name: string;
  __type?: T;
}

interface Provider<T = any> {
  token: InjectionToken<T>;
  useClass?: new (...args: any[]) => T;
  useFactory?: (...args: any[]) => T | Promise<T>;
  useValue?: T;
  scope?: InjectionScope;
}

class DIContainer {
  private providers = new Map<InjectionToken, Provider>();
  private instances = new Map<InjectionToken, any>();
  private factories = new Map<InjectionToken, (...args: any[]) => any>();

  register<T>(provider: Provider<T>): this {
    this.providers.set(provider.token, provider);
    if (provider.useValue !== undefined) {
      this.instances.set(provider.token, provider.useValue);
    }
    if (provider.useFactory) {
      this.factories.set(provider.token, provider.useFactory);
    }
    return this;
  }

  async resolve<T>(token: InjectionToken<T>): Promise<T> {
    const existingInstance = this.instances.get(token);
    if (existingInstance !== undefined) {
      return existingInstance;
    }

    const provider = this.providers.get(token);
    if (!provider) {
      throw new Error(`未注册的依赖: ${token.name}`);
    }

    let instance: T;

    if (provider.useClass) {
      instance = await this.createInstance(provider.useClass);
    } else if (provider.useFactory) {
      const deps = await this.resolveFactoryDeps(provider.useFactory);
      instance = await provider.useFactory(...deps);
    } else {
      throw new Error(`Provider ${token.name} 缺少实现`);
    }

    if (provider.scope !== InjectionScope.Transient) {
      this.instances.set(token, instance);
    }

    return instance;
  }

  private async createInstance<T>(TargetClass: new (...args: any[]) => T): Promise<T> {
    const injections: { index: number; token: InjectionToken }[] =
      Reflect.getMetadata(INJECT_METADATA_KEY, TargetClass) || [];

    const args: any[] = [];
    for (const injection of injections) {
      args[injection.index] = await this.resolve(injection.token);
    }

    return new TargetClass(...args);
  }

  private async resolveFactoryDeps(
    factory: (...args: any[]) => any
  ): Promise<any[]> {
    return [];
  }

  createScope(): DIContainer {
    const scoped = new DIContainer();
    for (const [token, provider] of this.providers) {
      scoped.providers.set(token, provider);
    }
    for (const [token, instance] of this.instances) {
      scoped.instances.set(token, instance);
    }
    return scoped;
  }
}

const globalContainer = new DIContainer();

DI装饰器

function Injectable(scope: InjectionScope = InjectionScope.Singleton) {
  return function <T extends { new (...args: any[]): any }>(
    target: T,
    context: ClassDecoratorContext
  ) {
    Reflect.defineMetadata(INJECTABLE_METADATA_KEY, true, target);
    Reflect.defineMetadata(SCOPE_METADATA_KEY, scope, target);

    const token: InjectionToken = { name: target.name };
    globalContainer.register({
      token,
      useClass: target,
      scope,
    });

    return target;
  };
}

function Inject(token: InjectionToken) {
  return function (
    target: any,
    context: ClassMethodDecoratorContext | ClassFieldDecoratorContext
  ) {
    if (context.kind === 'method') {
      const existingInjections: { index: number; token: InjectionToken }[] =
        Reflect.getMetadata(INJECT_METADATA_KEY, target) || [];
      existingInjections.push({ index: 0, token });
      Reflect.defineMetadata(INJECT_METADATA_KEY, existingInjections, target);
    }
  };
}

function AutoInject(token?: InjectionToken) {
  return function (
    target: any,
    context: ClassFieldDecoratorContext
  ) {
    const resolvedToken = token || { name: String(context.name) };

    return {
      get(this: any) {
        if (!this[`__injected_${String(context.name)}`]) {
          this[`__injected_${String(context.name)}`] = globalContainer.resolve(resolvedToken);
        }
        return this[`__injected_${String(context.name)}`];
      },
    };
  };
}

使用示例

const TOKENS = {
  Logger: { name: 'Logger' } as InjectionToken<LoggerService>,
  Database: { name: 'Database' } as InjectionToken<DatabaseService>,
  UserRepository: { name: 'UserRepository' } as InjectionToken<UserRepository>,
  UserService: { name: 'UserService' } as InjectionToken<UserService>,
};

@Injectable(InjectionScope.Singleton)
class LoggerService {
  log(message: string, ...args: any[]) {
    console.log(`[Logger] ${message}`, ...args);
  }

  error(message: string, ...args: any[]) {
    console.error(`[Logger] ${message}`, ...args);
  }
}

@Injectable(InjectionScope.Singleton)
class DatabaseService {
  private connected = false;

  async connect(): Promise<void> {
    this.connected = true;
    console.log('[DB] 数据库连接成功');
  }

  async query<T>(sql: string, params?: any[]): Promise<T[]> {
    if (!this.connected) throw new Error('数据库未连接');
    console.log(`[DB] 执行查询: ${sql}`);
    return [] as T[];
  }
}

@Injectable(InjectionScope.Transient)
class UserRepository {
  constructor(
    private db: DatabaseService,
    private logger: LoggerService
  ) {}

  async findById(id: string) {
    this.logger.log(`查找用户: ${id}`);
    return this.db.query('SELECT * FROM users WHERE id = $1', [id]);
  }
}

@Injectable(InjectionScope.Singleton)
class UserService {
  @AutoInject(TOKENS.UserRepository)
  accessor userRepo!: UserRepository;

  @AutoInject(TOKENS.Logger)
  accessor logger!: LoggerService;

  async getUser(id: string) {
    this.logger.log(`获取用户: ${id}`);
    return this.userRepo.findById(id);
  }
}

globalContainer.register({ token: TOKENS.Logger, useClass: LoggerService });
globalContainer.register({ token: TOKENS.Database, useClass: DatabaseService });
globalContainer.register({ token: TOKENS.UserRepository, useClass: UserRepository });
globalContainer.register({ token: TOKENS.UserService, useClass: UserService });

const userService = await globalContainer.resolve(TOKENS.UserService);
await userService.getUser('user-001');

模式6:装饰器组合与管道模式

装饰器最优雅的用法是组合——多个装饰器按管道顺序执行,每个装饰器只关注一个切面,通过组合实现复杂功能。

管道式装饰器组合

interface PipeContext<TInput, TOutput> {
  input: TInput;
  output?: TOutput;
  metadata: Map<string, any>;
  skip?: boolean;
  error?: Error;
}

type PipeHandler<TInput, TOutput> = (
  context: PipeContext<TInput, TOutput>,
  next: () => Promise<PipeContext<TInput, TOutput>>
) => Promise<PipeContext<TInput, TOutput>>;

class Pipeline<TInput, TOutput> {
  private handlers: PipeHandler<TInput, TOutput>[] = [];

  pipe(handler: PipeHandler<TInput, TOutput>): this {
    this.handlers.push(handler);
    return this;
  }

  async execute(input: TInput): Promise<TOutput> {
    let context: PipeContext<TInput, TOutput> = {
      input,
      metadata: new Map(),
    };

    let index = 0;

    const dispatch = async (): Promise<PipeContext<TInput, TOutput>> => {
      if (index >= this.handlers.length || context.skip) {
        return context;
      }

      const handler = this.handlers[index++];
      return handler(context, dispatch);
    };

    context = await dispatch();

    if (context.error) {
      throw context.error;
    }

    return context.output as TOutput;
  }
}

装饰器管道组合

function Timeout(ms: number) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const originalMethod = target.value;

    async function replacementMethod(this: any, ...args: any[]) {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), ms);

      try {
        const result = await Promise.race([
          originalMethod.apply(this, args),
          new Promise((_, reject) =>
            setTimeout(() => reject(new Error(`方法超时: ${ms}ms`)), ms)
          ),
        ]);
        clearTimeout(timeoutId);
        return result;
      } catch (error) {
        clearTimeout(timeoutId);
        throw error;
      }
    }

    return replacementMethod;
  };
}

function Debounce(ms: number) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const originalMethod = target.value;
    let timeoutId: ReturnType<typeof setTimeout> | undefined;

    function replacementMethod(this: any, ...args: any[]) {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }

      return new Promise((resolve) => {
        timeoutId = setTimeout(() => {
          resolve(originalMethod.apply(this, args));
        }, ms);
      });
    }

    return replacementMethod;
  };
}

function Throttle(ms: number) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const originalMethod = target.value;
    let lastCallTime = 0;

    function replacementMethod(this: any, ...args: any[]) {
      const now = Date.now();
      if (now - lastCallTime < ms) {
        return undefined;
      }
      lastCallTime = now;
      return originalMethod.apply(this, args);
    }

    return replacementMethod;
  };
}

function Memoize(keyResolver?: (...args: any[]) => string) {
  return function (
    target: DecoratorTarget,
    context: ClassMethodDecoratorContext
  ) {
    const originalMethod = target.value;
    const cache = new Map<string, { value: any; expireAt: number }>();
    const defaultTtl = 5 * 60 * 1000;

    async function replacementMethod(this: any, ...args: any[]) {
      const key = keyResolver ? keyResolver(...args) : JSON.stringify(args);
      const cached = cache.get(key);

      if (cached && cached.expireAt > Date.now()) {
        return cached.value;
      }

      const result = await originalMethod.apply(this, args);
      cache.set(key, { value: result, expireAt: Date.now() + defaultTtl });
      return result;
    }

    return replacementMethod;
  };
}

组合使用示例

class SearchService {
  @logMinimal
  @Timeout(5000)
  @Memoize((query: string) => `search:${query}`)
  async search(query: string): Promise<string[]> {
    const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
    return response.json();
  }

  @Debounce(300)
  @logMinimal
  async autoComplete(prefix: string): Promise<string[]> {
    const response = await fetch(`/api/suggest?q=${encodeURIComponent(prefix)}`);
    return response.json();
  }

  @Throttle(1000)
  @logMinimal
  trackSearch(query: string): void {
    console.log(`搜索追踪: ${query}`);
  }
}

装饰器执行顺序

方法调用 → @logMinimal → @Timeout → @Memoize → 原始方法
                                                      │
方法返回 ← @logMinimal ← @Timeout ← @Memoize ← 原始结果

注意:TC39装饰器执行顺序是从下到上(最靠近方法的装饰器先执行包装)
但运行时调用是从外到内(最外层装饰器先拦截请求)

5个常见坑及解决方案

坑1:装饰器中this指向丢失

// 错误写法
function badDecorator(
  target: DecoratorTarget,
  context: ClassMethodDecoratorContext
) {
  return function (...args: any[]) {
    // this 指向可能丢失!
    return target.value(...args);
  };
}

// 正确写法
function goodDecorator(
  target: DecoratorTarget,
  context: ClassMethodDecoratorContext
) {
  return function (this: any, ...args: any[]) {
    return target.value.apply(this, args);
  };
}

坑2:异步方法装饰器忘记返回Promise

// 错误写法
function badAsyncDecorator(
  target: DecoratorTarget,
  context: ClassMethodDecoratorContext
) {
  return function (this: any, ...args: any[]) {
    const result = target.value.apply(this, args);
    // 忘记处理Promise,导致错误无法被捕获
    console.log('执行完成');
    return result;
  };
}

// 正确写法
function goodAsyncDecorator(
  target: DecoratorTarget,
  context: ClassMethodDecoratorContext
) {
  return async function (this: any, ...args: any[]) {
    try {
      const result = await target.value.apply(this, args);
      console.log('执行完成');
      return result;
    } catch (error) {
      console.error('执行失败', error);
      throw error;
    }
  };
}

坑3:装饰器顺序错误导致逻辑混乱

// 错误顺序:缓存在验证之前,可能缓存非法数据
class BadService {
  @Cache()
  @Validate()
  async getData(id: string) { /* ... */ }
}

// 正确顺序:验证在缓存之前
class GoodService {
  @Validate()
  @Cache()
  async getData(id: string) { /* ... */ }
}

// 记忆口诀:验证 → 缓存 → 日志 → 业务

坑4:addInitializer中访问实例属性

// 错误写法:addInitializer在构造函数之前执行
function badInitDecorator(
  target: any,
  context: ClassFieldDecoratorContext
) {
  context.addInitializer(function (this: any) {
    // this的属性可能还未初始化!
    console.log(this.name);
  });
}

// 正确写法:在addInitializer中只注册钩子,不访问实例属性
function goodInitDecorator(
  target: any,
  context: ClassFieldDecoratorContext
) {
  context.addInitializer(function (this: any) {
    // 只做元数据注册,不访问实例属性
    const existingInits: string[] = Reflect.getMetadata(
      Symbol('inits'),
      this.constructor
    ) || [];
    existingInits.push(String(context.name));
    Reflect.defineMetadata(Symbol('inits'), existingInits, this.constructor);
  });
}

坑5:Legacy装饰器和TC39装饰器混用

// tsconfig.json 中不能同时启用两种模式
// 错误配置:
{
  "compilerOptions": {
    "experimentalDecorators": true,  // Legacy模式
    "decorators": { "version": "2022-03" }  // TC39模式
    // 两者互斥!只能选一个
  }
}

// 正确配置(TC39标准装饰器):
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "experimentalDecorators": false
    // TypeScript 5.8+ 默认使用TC39标准装饰器
  }
}

// 迁移策略:逐文件迁移,不要混用
// 1. 新文件使用TC39装饰器
// 2. 旧文件保持Legacy,通过eslint规则限制
// 3. 完成迁移后关闭experimentalDecorators

10个常见报错排查

报错信息 原因 解决方案
Decorators are not enabled tsconfig未启用装饰器 设置"experimentalDecorators": true(Legacy)或升级TS 5.8+
Invalid decorator context kind 装饰器类型与目标不匹配 检查context.kind,确保方法装饰器用于方法
Cannot read property 'value' of undefined Legacy装饰器写法用于TC39 TC39装饰器第一个参数是{ value, ... }对象
this is undefined in decorator 箭头函数导致this丢失 使用function关键字定义replacementMethod
Decorators must return void or replace value 装饰器返回了非法值 方法装饰器返回函数,类装饰器返回类
Metadata reflection not available 未安装reflect-metadata npm install reflect-metadata并在入口导入
Decorator applied to constructor parameter TC39不支持参数装饰器 改用方法装饰器+运行时校验
Circular dependency detected DI容器循环依赖 使用LazyInject或重构依赖关系
Property 'addInitializer' does not exist TypeScript版本过低 升级到TypeScript 5.0+
Experimental feature warning 使用了Legacy装饰器 迁移到TC39标准装饰器

进阶优化技巧

1. 装饰器性能优化:惰性初始化

function LazyInit(factory: () => any) {
  return function (
    target: any,
    context: ClassFieldDecoratorContext
  ) {
    return {
      get(this: any) {
        const key = `__lazy_${String(context.name)}`;
        if (!this[key]) {
          this[key] = factory.call(this);
        }
        return this[key];
      },
    };
  };
}

class ExpensiveService {
  @LazyInit(() => new HeavyComputation())
  accessor engine: any;
}

2. 条件装饰器

function Conditional(
  condition: () => boolean,
  decorator: Function
) {
  return function (...args: any[]) {
    if (condition()) {
      return (decorator as any)(...args);
    }
    return undefined;
  };
}

const isProduction = () => process.env.NODE_ENV === 'production';

class ApiService {
  @Conditional(isProduction, logMinimal)
  async fetchData(url: string) {
    return fetch(url).then((r) => r.json());
  }
}

3. 装饰器元数据序列化

const SERIALIZABLE_KEY = Symbol('serializable');

interface SerializableField {
  name: string;
  type: string;
  serializer?: (value: any) => any;
  deserializer?: (value: any) => any;
}

function Serializable(options?: Partial<SerializableField>) {
  return function (
    target: any,
    context: ClassFieldDecoratorContext
  ) {
    context.addInitializer(function (this: any) {
      const fields: SerializableField[] = Reflect.getMetadata(
        SERIALIZABLE_KEY,
        this.constructor
      ) || [];

      fields.push({
        name: String(context.name),
        type: options?.type || 'string',
        serializer: options?.serializer,
        deserializer: options?.deserializer,
      });

      Reflect.defineMetadata(SERIALIZABLE_KEY, fields, this.constructor);
    });
  };
}

function toJSON(instance: any): Record<string, any> {
  const fields: SerializableField[] = Reflect.getMetadata(
    SERIALIZABLE_KEY,
    instance.constructor
  ) || [];

  const result: Record<string, any> = {};
  for (const field of fields) {
    const value = instance[field.name];
    result[field.name] = field.serializer ? field.serializer(value) : value;
  }
  return result;
}

4. 装饰器调试工具

function DebugDecorator(
  target: DecoratorTarget,
  context: ClassMethodDecoratorContext
) {
  const methodName = String(context.name);

  return function (this: any, ...args: any[]) {
    console.group(`🔍 ${this.constructor.name}.${methodName}`);
    console.log('参数:', args);
    console.trace('调用栈');

    try {
      const result = target.value.apply(this, args);
      if (result instanceof Promise) {
        return result.then(
          (value) => {
            console.log('异步结果:', value);
            console.groupEnd();
            return value;
          },
          (error) => {
            console.error('异步错误:', error);
            console.groupEnd();
            throw error;
          }
        );
      }

      console.log('同步结果:', result);
      console.groupEnd();
      return result;
    } catch (error) {
      console.error('同步错误:', error);
      console.groupEnd();
      throw error;
    }
  };
}

对比分析:TC39装饰器 vs Legacy装饰器 vs 装饰器工厂

特性 TC39标准装饰器 Legacy装饰器 装饰器工厂
规范状态 Stage 3.7,即将进入Stage 4 已废弃,仅向后兼容 基于TC39的工厂模式
TypeScript支持 5.0+原生支持 experimentalDecorators 基于TC39
执行顺序 从下到上(靠近方法的先包装) 从上到下 同TC39
修改方式 返回新值替换,不修改原始 直接修改描述符 同TC39
参数装饰器 不支持 支持 不支持
元数据支持 需手动或reflect-metadata emitDecoratorMetadata 需手动
this绑定 安全(通过replacement函数) 需注意 安全
addInitializer 支持(实例化钩子) 不支持 支持
不可变性 高(函数式替换) 低(可变修改)
生态兼容 主流框架正在迁移 当前主流 推荐
未来方向 标准规范 逐步淘汰 最佳实践

迁移检查清单

Legacy → TC39 迁移步骤:
□ 1. 升级TypeScript到5.0+
□ 2. 关闭experimentalDecorators
□ 3. 将装饰器参数从(target, key, descriptor)改为(target, context)
□ 4. 将descriptor.value改为target.value
□ 5. 将descriptor.get/set改为target.get/set
□ 6. 使用context.addInitializer替代constructor注入
□ 7. 移除参数装饰器,改用方法装饰器+运行时校验
□ 8. 更新reflect-metadata调用方式
□ 9. 运行完整测试套件
□ 10. 逐步迁移,不要一次性改完

在线工具推荐

相关阅读

外部参考


总结

TypeScript 5.8装饰器中间件在2026年已经从实验特性走向生产就绪。TC39标准装饰器的不可变性、函数式替换、addInitializer钩子等特性,让装饰器中间件成为实现AOP架构、依赖注入、参数验证的利器。

核心要点回顾

  1. 方法拦截器:日志、计时、重试等横切逻辑,不侵入业务代码
  2. 类转换器:元数据注册、路由映射、ORM映射,通过addInitializer注入
  3. 参数验证:类型校验、Schema校验,在方法执行前拦截非法输入
  4. AOP中间件链:Auth→Cache→Retry→Log的管道式执行,解耦横切关注点
  5. 依赖注入:装饰器声明依赖,容器自动解析,支持Singleton/Transient/Request作用域
  6. 装饰器组合:管道模式组合多个装饰器,每个装饰器只关注一个切面

选型建议:新项目直接使用TC39标准装饰器,旧项目制定迁移计划逐步过渡。装饰器中间件的核心价值在于——让业务代码只关注业务,横切逻辑交给装饰器

本站提供浏览器本地工具,免注册即可试用 →

#TypeScript#装饰器#Decorator#AOP#元编程#中间件#2026#编程语言