如何在TypeScript中使用装饰器?

解读

装饰器是TypeScript中用于增强类、方法、属性等元数据的高级语法特性,能够实现代码的可配置化、模块化和可维护性提升。该问题考察候选人对装饰器机制的理解、实际应用能力以及对TypeScript类型系统与装饰器结合的掌握,属于中等偏难的技术问题,常出现在中高级工程师面试中。

知识点

  1. 装饰器定义:装饰器本质是函数,通过元编程在编译时修改类声明或成员的结构。
  2. 装饰器语法:包括类装饰器、方法装饰器、属性装饰器、参数装饰器四种类型。
  3. 装饰器参数:通过target、name、descriptor等参数获取目标元数据信息。
  4. 装饰器工厂:用于封装装饰器逻辑,支持参数传入。
  5. 装饰器组合:多个装饰器按顺序应用时的执行顺序规则。
  6. 编译器配置:需在tsconfig.json中启用"experimentalDecorators": true。
  7. 元数据应用:结合Reflect API实现装饰器的元数据读取与处理。

答案

TypeScript中使用装饰器需遵循以下步骤:

1. 基础语法

装饰器通过@符号标注,例如:

// 类装饰器  
@Logger  
class MyClass {  
  // 方法装饰器  
  @Validate()  
  myMethod() {  
    // 属性装饰器  
    @ReadOnly()  
    myProperty: string;  
  }  
}

2. 参数传递

装饰器可接收参数,需通过工厂函数实现:

function Log(target: any, propertyName: string) {  
  console.log(`Property ${propertyName} in ${target.constructor.name} is being logged`);  
}  

// 方法装饰器带参数  
function Validate(value: string) {  
  return function (target: any, methodName: string, descriptor: PropertyDescriptor) {  
    console.log(`Validating ${methodName} with ${value}`);  
  };  
}  

3. 装饰器执行顺序

多个装饰器按从下到上的顺序执行,例如:

@DecoratorA  
@DecoratorB  
class C {  
  @DecoratorX  
  @DecoratorY  
  method() {}  
}

DecoratorY会先于DecoratorX执行,DecoratorB会先于DecoratorA执行。

4. 编译器配置

需在tsconfig.json中启用装饰器支持:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

5. 元数据处理

通过Reflect API读取装饰器信息:

function MyDecorator() {  
  return function (target: any, propertyName: string) {  
    Reflect.defineMetadata('custom', 'value', target, propertyName);  
  };  
}  

class D {  
  @MyDecorator()  
  myProperty: string;  
}  

// 读取元数据  
const metadata = Reflect.getMetadata('custom', D, 'myProperty');  
console.log(metadata); // 输出: 'value'  

拓展思考

  • 装饰器的底层原理:装饰器在编译时被转换为对类声明的修改,需理解其如何通过AST(抽象语法树)实现功能扩展。
  • 性能考量:装饰器会增加编译时间,需在大型项目中权衡其使用场景。
  • 类型系统结合:装饰器可与类型注解联动,例如通过@Injectable实现依赖注入的类型校验。
  • 框架集成实践:在React中,装饰器可用于组件状态管理(如@Component);在Vue中,可通过装饰器实现响应式属性的自动注册。
  • 常见错误规避:避免在装饰器中直接修改目标对象,应通过PropertyDescriptor或Reflect进行元数据操作。