TypeScript 的装饰器(Decorators)是一个实验性的特性,用于修改或增强类及其成员(如属性、方法等)的行为。装饰器是一种特殊类型的声明,能够在类定义时附加元数据,修改类的行为或添加功能。虽然它是一个实验性的特性,但在实际开发中非常有用,特别是当你需要在 TypeScript 中进行更复杂的类操作时。
基本概念
装饰器是一种函数,它可以附加到类、类的方法、类的属性、类的访问器(getter/setter)等。装饰器的作用是为被装饰的目标提供附加功能或修改其行为。
在 TypeScript 中使用装饰器之前,需要在 tsconfig.json
文件中启用 experimentalDecorators
选项:
{
"compilerOptions": {
"experimentalDecorators": true
}
}
装饰器的类型
-
类装饰器 (Class Decorator)
- 类装饰器是应用于类构造函数的函数。
- 通过它,你可以修改类的构造函数,或者添加一些额外的功能。
示例:
function Injectable(constructor: Function) { console.log(`Injectable decorator applied to ${constructor.name}`); } @Injectable class MyService { constructor() { console.log('MyService created'); } }
在这个例子中,
@Injectable
是一个类装饰器,它会在MyService
类定义时被调用。 -
方法装饰器 (Method Decorator)
- 方法装饰器应用于类的实例方法。它接收三个参数:目标对象、方法名称和方法描述符。
示例:
function Log(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`Method ${String(propertyKey)} called with args: ${args}`); return originalMethod.apply(this, args); }; } class MyClass { @Log myMethod(arg: number) { console.log('Inside myMethod'); } } const instance = new MyClass(); instance.myMethod(42);
在这个例子中,
@Log
是一个方法装饰器,它会在myMethod
方法被调用时打印调用日志。 -
属性装饰器 (Property Decorator)
- 属性装饰器应用于类的属性。它接收两个参数:目标对象和属性名称。
示例:
function ReadOnly(target: any, propertyKey: string | symbol) { const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey); if (descriptor) { descriptor.writable = false; Object.defineProperty(target, propertyKey, descriptor); } } class MyClass { @ReadOnly myProperty: number = 42; } const instance = new MyClass(); instance.myProperty = 24; // 这将不会生效,因为属性是只读的
在这个例子中,
@ReadOnly
是一个属性装饰器,它使得myProperty
属性变为只读。 -
访问器装饰器 (Accessor Decorator)
- 访问器装饰器应用于类的访问器(getter/setter)。它接收三个参数:目标对象、访问器名称和访问器描述符。
示例:
function UpperCase(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) { const originalGet = descriptor.get; descriptor.get = function() { const value = originalGet!.apply(this); return value.toUpperCase(); }; } class MyClass { private _name: string = 'hello'; @UpperCase get name() { return this._name; } } const instance = new MyClass(); console.log(instance.name); // 输出: HELLO
在这个例子中,
@UpperCase
是一个访问器装饰器,它将name
属性的值转换为大写。
使用场景
- 依赖注入:装饰器常用于依赖注入框架中,例如 Angular 使用装饰器来标记依赖关系。
- 日志记录:使用方法装饰器来记录方法调用情况。
- 权限控制:通过装饰器来实现方法的权限控制或访问限制。
- 属性验证:使用属性装饰器来进行属性的验证和处理。
注意事项
- 实验性特性:装饰器目前是实验性的特性,可能会在未来版本中发生变化。
- 与 JavaScript 标准的兼容性:装饰器并不是 JavaScript 的标准特性,使用它们时要注意与 JavaScript 标准的兼容性问题。
通过这些装饰器,你可以在 TypeScript 中编写更加灵活和可扩展的代码。