【发布时间】:2016-05-21 23:16:47
【问题描述】:
有没有办法在 TypeScript 中进行代码编织?
我要做的是在我的 TypeScript 应用程序中的每个函数的第一行注入一段代码,我不会手动执行此操作(这种手动方法很乏味且容易出错)。
【问题讨论】:
标签: typescript compile-time-weaving
有没有办法在 TypeScript 中进行代码编织?
我要做的是在我的 TypeScript 应用程序中的每个函数的第一行注入一段代码,我不会手动执行此操作(这种手动方法很乏味且容易出错)。
【问题讨论】:
标签: typescript compile-time-weaving
虽然不是真正的编译-time weaving,但您只能使用method decorators 在运行时 使用附加功能包装这些方法。考虑这个示例方法装饰器,它使调用还将接收到的参数记录到控制台中:
// 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 个参数:
方法装饰器返回单个属性描述符,它是类型上原始方法的替换。
【讨论】: