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;

  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#编程语言