ton*_*y19 98 typescript typescript2.0
当我启用noImplicitThis时tsconfig.json,我得到以下代码的此错误:
Run Code Online (Sandbox Code Playgroud)'this' implicitly has type 'any' because it does not have a type annotation.
class Foo implements EventEmitter {
on(name: string, fn: Function) { }
emit(name: string) { }
}
const foo = new Foo();
foo.on('error', function(err: any) {
console.log(err);
this.emit('end'); // error: `this` implicitly has type `any`
});
Run Code Online (Sandbox Code Playgroud)
将typed添加this到回调参数会导致相同的错误:
foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
Run Code Online (Sandbox Code Playgroud)
解决方法是替换this为对象:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
Run Code Online (Sandbox Code Playgroud)
但是这个错误的正确解决方法是什么?
更新:事实证明this,在回调中添加一个类型确实可以解决错误.我看到了错误,因为我正在使用带有类型注释的箭头函数this:
ton*_*y19 105
通过this使用类型注释作为第一个回调参数插入,确实可以修复错误.我这样做的尝试是通过同时将回调更改为箭头函数来实现的:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
Run Code Online (Sandbox Code Playgroud)
应该是这样的:
foo.on('error', function(this: Foo, err: any) {
Run Code Online (Sandbox Code Playgroud)
或这个:
foo.on('error', function(this: typeof foo, err: any) {
Run Code Online (Sandbox Code Playgroud)
创建了GitHub 问题以改进编译器的错误消息,并使用this和箭头函数突出显示实际的语法错误.
小智 21
在 tsconfig.json 中将“noImplicitAny”更改为 false 没有帮助。尝试"noImplicitThis": false在 tsconfig.json 中执行
mus*_*una 11
对于带有配置的方法装饰器声明,"noImplicitAny": true,
您可以显式指定此变量的类型,具体取决于@tony19的答案
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60058 次 |
| 最近记录: |