阅24
TypeScript装饰器教程
TypeScript 装饰器教程
装饰器(Decorators)是TypeScript中的一个重要特性,它提供了一种在类声明、方法、访问器、属性或参数上添加元编程语法的方式。装饰器使用@expression的形式,其中expression必须求值为一个函数,该函数会在运行时被调用。
装饰器基础
启用装饰器
在tsconfig.json中启用装饰器支持:
json{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } }
装饰器类型
TypeScript支持以下几种装饰器:
-
类装饰器
-
方法装饰器
-
访问器装饰器
-
属性装饰器
-
参数装饰器
类装饰器
类装饰器应用于类构造函数,可以用来观察、修改或替换类定义。
typescriptfunction classDecorator(constructor: Function) { console.log('类装饰器被调用'); } @classDecorator class MyClass { constructor() { console.log('类实例被创建'); } } // 输出: // 类装饰器被调用 // 类实例被创建
修改类定义
typescriptfunction addGreeting(constructor: Function) { constructor.prototype.greet = function() { console.log('Hello!'); }; } @addGreeting class Person { name: string; constructor(name: string) { this.name = name; } } const person = new Person('John'); (person as any).greet(); // 输出: Hello!
方法装饰器
方法装饰器应用于类的方法上。
typescriptfunction logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`调用方法: ${propertyKey},参数: ${JSON.stringify(args)}`); const result = originalMethod.apply(this, args); console.log(`方法 ${propertyKey} 返回: ${result}`); return result; }; return descriptor; } class Calculator { @logMethod add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); calc.add(2, 3); // 输出: // 调用方法: add,参数: [2,3] // 方法 add 返回: 5
访问器装饰器
访问器装饰器应用于类的getter或setter上。
typescriptfunction configurable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.configurable = value; }; } class Point { private _x: number; private _y: number; constructor(x: number, y: number) { this._x = x; this._y = y; } @configurable(false) get x() { return this._x; } @configurable(true) get y() { return this._y; } }
属性装饰器
属性装饰器应用于类的属性上。
typescriptfunction format(formatString: string) { return function (target: any, propertyKey: string) { let value = target[propertyKey]; const getter = function() { return value; }; const setter = function(newVal: string) { value = `${formatString} ${newVal}`; }; Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true }); }; } class Greeter { @format('Hello') greeting: string; constructor(message: string) { this.greeting = message; } greet() { return this.greeting; } } const greeter = new Greeter('World'); console.log(greeter.greet()); // 输出: Hello World
参数装饰器
参数装饰器应用于类构造器或方法的参数上。
typescriptfunction validateParam(target: any, propertyKey: string, parameterIndex: number) { console.log(`参数装饰器应用于方法 ${propertyKey} 的第 ${parameterIndex} 个参数`); } class Validator { validate(@validateParam input: string) { console.log(`验证输入: ${input}`); } } const validator = new Validator(); validator.validate('test'); // 输出: // 参数装饰器应用于方法 validate 的第 0 个参数 // 验证输入: test
装饰器工厂
装饰器工厂是一个返回装饰器函数的函数,允许你自定义装饰器的行为。
typescriptfunction logWithMessage(message: string) { return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log(message); return originalMethod.apply(this, args); }; return descriptor; }; } class Messenger { @logWithMessage('即将发送消息') send(message: string) { console.log(`发送: ${message}`); } } const messenger = new Messenger(); messenger.send('Hello!'); // 输出: // 即将发送消息 // 发送: Hello!
装饰器执行顺序
装饰器的应用顺序如下:
-
参数装饰器,然后依次是方法装饰器、访问器装饰器或属性装饰器应用到每个实例成员
-
参数装饰器,然后依次是方法装饰器、访问器装饰器或属性装饰器应用到每个静态成员
-
参数装饰器应用到构造函数
-
类装饰器应用到类
实际应用示例
1. 日志记录装饰器
typescriptfunction logClass(target: Function) { console.log(`类 ${target.name} 被定义`); } function logMethod(target: any, key: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`调用方法 ${key} 参数: ${args}`); const result = original.apply(this, args); console.log(`方法 ${key} 返回: ${result}`); return result; }; return descriptor; } @logClass class MathOperations { @logMethod add(a: number, b: number): number { return a + b; } @logMethod multiply(a: number, b: number): number { return a * b; } } const math = new MathOperations(); math.add(2, 3); math.multiply(4, 5);
2. 权限控制装饰器
typescriptfunction adminOnly(target: any, key: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function(...args: any[]) { const user = { role: 'user' }; // 假设从某处获取用户信息 if (user.role !== 'admin') { throw new Error('只有管理员可以执行此操作'); } return original.apply(this, args); }; return descriptor; } class UserManager { @adminOnly deleteUser(userId: number) { console.log(`用户 ${userId} 已被删除`); } } const manager = new UserManager(); try { manager.deleteUser(1); // 抛出错误: 只有管理员可以执行此操作 } catch (e) { console.error(e.message); }
元数据反射
TypeScript可以与reflect-metadata库一起使用,为装饰器提供更强大的元数据功能。
首先安装:
bashnpm install reflect-metadata
然后使用:
typescriptimport 'reflect-metadata'; function logType(target: any, key: string) { const type= Reflect.getMetadata('design:type', target, key); console.log(`${key} 类型: ${type.name}`); } class Example { @logType public name: string = 'John'; @logType public age: number = 30; } // 输出: // name 类型: String // age 类型: Number
总结
TypeScript装饰器提供了一种强大的方式来修改或扩展类和类成员的行为。它们可以用于:
-
日志记录
-
权限控制
-
验证
-
依赖注入
-
性能测量
-
和其他横切关注点(AOP)
装饰器目前仍然是实验性特性,但已经被许多流行的框架(如Angular、NestJS等)广泛使用。
加载中...