【发布时间】:2019-05-19 02:59:15
【问题描述】:
我正在尝试编写一个简单的方法装饰器,在调用原始方法之前执行一些简单的逻辑。我能找到的所有示例都归结为最后调用originalMethod.apply(this, args) - 但是在tsconfig.json 中启用noImplicitThis,我收到以下错误:
[eval].ts(1,224): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
我尝试通过调用originalMethod.apply(this as any, args) 解决问题,但错误仍然存在。
问题:是否有任何变通方法可以调用原始方法,无需为整个项目禁用noImplicitThis?
最小示例 -- 与 noImplicitAny 禁用:
function logBeforeCall1(): originalMethodDecorator {
return function(
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor,
): PropertyDescriptor {
const originalMethod = descriptor.value;
descriptor.value = (...args: any[]) => {
console.log('hello!');
return originalMethod.apply(this, args);
};
return descriptor;
};
}
class Test1 {
private num: number = 1;
@logBeforeCall1()
test(next: number): void {
console.log(this.num, '->', next);
this.num = next;
}
}
- 我已经知道装饰器无法访问特定的对象实例(参见例如this question),但在上面的示例中使用
this可以工作 - 装饰器的官方文档使用我示例中的构造(参见Property Decorators section),所以它有效,但与
noImplicitThis编译器选项冲突...
【问题讨论】:
标签: typescript decorator typescript-decorator