有没有办法在 TypeScript 中进行代码编织?
我想要做的是注入一段代码作为我的 TypeScript 应用程序中每个函数的第一行,我不会手动执行此操作(这种手动方法很乏味且容易出错)。
有没有办法在 TypeScript 中进行代码编织?
我想要做的是注入一段代码作为我的 TypeScript 应用程序中每个函数的第一行,我不会手动执行此操作(这种手动方法很乏味且容易出错)。
虽然不是真正的编译时编织,但仅对于类方法,您可以使用方法装饰器在运行时使用附加功能包装这些方法。考虑这个示例方法装饰器,它使调用还将接收到的参数记录到控制台中:
// the method decorator function
function log(target: Object, key: string, descriptor: any) {
// replace original property descriptor of method with the following one:
return {
// the new method:
value: function (...args: any[]) {
// log arguments
console.log(args);
// invoke the original method as part of the new method,
// and return its returned value (if any)
return descriptor.value.apply(this, args);
}
};
}
将这个装饰器应用到一个方法上很简单:
class Calculator {
@log
add(a: number, b: number) {
return a + b;
}
}
快速解释:Typescript 中的方法装饰器具有以下签名:
<T>(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor<T>) => PropertyDescriptor<T> | void;
换句话说,方法装饰器接受 3 个参数:
方法装饰器返回单个属性描述符,它是类型上原始方法的替换。