TypeScript中的装饰器是一种特殊函数,用于通过添加元数据或修改类、方法、属性或参数的行为来增强代码功能。以下是关于TypeScript装饰器的详细说明:
核心概念启用装饰器需在tsconfig.json中启用experimentalDecorators选项:
{ "compilerOptions": { "experimentalDecorators": true }}装饰器类型与实现1. 类装饰器(组件装饰器示例)功能:为类添加元数据(如组件名称)。实现步骤:
- 定义装饰器:接收参数并返回一个函数,该函数修改目标类的原型。function Component(name: string) { return function (constructor: Function) { constructor.prototype.componentName = name; };}
- 应用装饰器:通过@符号附加到类。@Component('MyComponent')class MyComponent { constructor() { console.log(`Component name: ${this.componentName}`); }}
- 测试效果:const instance = new MyComponent(); // 输出: Component name: MyComponent
2. 属性装饰器(输入装饰器示例)功能:监听属性变更并执行自定义逻辑(如日志记录)。实现步骤:
- 定义装饰器:使用Object.defineProperty拦截属性的getter和setter。function Input() { return function (target: any, propertyKey: string) { let value: any; const getter = () => value; const setter = (newValue: any) => { console.log(`Property ${propertyKey} updated to: ${newValue}`); value = newValue; }; Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true }); };}
- 应用装饰器:附加到类的属性上。class MyComponent { @Input() public name: string; constructor(name: string) { this.name = name; }}
- 测试效果:const component = new MyComponent('Initial');component.name = 'New'; // 输出: Property name updated to: New
装饰器的优势- 代码可读性:通过声明式语法(如@Component)明确表达意图。
- 可维护性:集中管理横切关注点(如日志、元数据),减少重复代码。
- 灵活性:支持动态修改行为,适应不同场景需求。
高级应用- 反射元数据:结合reflect-metadata库实现更复杂的元数据管理。
- 框架集成:在Angular等框架中广泛用于依赖注入、路由配置等。
注意事项- 实验性特性:装饰器目前是TypeScript的实验性功能,未来版本可能调整语法。
- 性能影响:过度使用装饰器可能引入运行时开销,需权衡利弊。
通过掌握装饰器,开发者可以编写更简洁、模块化的代码,尤其适用于大型应用或框架开发。建议进一步探索官方文档和社区实践,以充分利用其潜力。