免责声明:我之前也曾在SO上发布过类似的问题。它们确实帮助我解决了一些TypeScript
编译器问题。但是我找不到一个有效的,完整的代码示例。
问题:我想在某些类方法上使用TypeScript
装饰器。但是问题是,如果我的方法实现为箭头函数,那么我将无法使用它们。我主要根据一些文章和SO帖子修改了我的代码(在运行时,它们被更多地视为类属性)
-
可选描述符
descriptor?: TypedPropertyDescriptor<any>
-
返回为
any
之后,编译器接受了装饰器,并且我的代码正在正确执行。但是我的装饰器代码无法正常工作。下面提供了简化的代码以供参考。使代码正常工作的任何帮助都将有所帮助。
装饰器
// Decorator declaration
export function LogPerf(
message = '',) {
return function (
target: any,key: string | symbol,descriptor?: TypedPropertyDescriptor<any>,) {
if (!descriptor) {
console.log('Logging performance of property...'); // This log doesn't execute at runtime
return;
}
// following log also doesn't work
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
const timeStartMilli: number = performance.now();
const result = original.apply(this,args);
const timeEndMilli: number = performance.now();
console.log(`Call to ${key.toString()} took ${timeEndMilli - timeStartMilli} ms. Message: ${message}`);
return result;
};
return descriptor as any;
};
}
还有一个示例用法,它不起作用。
注意:在普通实例方法上使用时,此方法工作正常。
// Decorater use (on class method,implemented as arrow function)
public export Someclass {
@LogPerf()
public myMethod = (
data: MyData,): Somehting => {
// Do something with data
}
}