que*_*zak 5 decorator typescript typescript-decorator
我正在尝试编写一个简单的方法装饰器,该装饰器在调用原始方法之前执行一些简单的逻辑。我可以找到的所有示例都归结为最后调用originalMethod.apply(this, args)-但在中noImplicitThis启用时tsconfig.json,出现以下错误:
[eval].ts(1,224): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
Run Code Online (Sandbox Code Playgroud)
我尝试通过致电解决此问题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;
}
}
Run Code Online (Sandbox Code Playgroud)
this在上述示例中使用noImplicitThis编译器选项冲突...感谢@Grassator 的灵感——这是一个有效的版本。不过,我不相信在 TypeScript 的当前状态下可以类型安全地完成此操作。
function logBeforeCall2(): originalMethodDecorator {
return function(
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor,
): PropertyDescriptor {
const originalMethod = descriptor.value;
descriptor.value = function(this: any, ...args: any[]): any {
console.log('hello!');
return originalMethod.apply(this, args);
};
return descriptor;
};
}
Run Code Online (Sandbox Code Playgroud)
...
> t2.test(5)
hello!
1 '->' 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
585 次 |
| 最近记录: |