在中启用noImplicitThis
时tsconfig.json
,以下代码会出现此错误:
'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`
});
将类型添加this
到回调参数会导致相同的错误:
foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
一种解决方法是this
用对象替换:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
但是,此错误的正确解决方法是什么?
更新:事实证明,将类型添加this
到回调确实可以解决该错误。我看到此错误是因为我正在使用带有类型注释的箭头功能this
:
您是否在TypeScript 2.1或夜间版本上尝试过此操作?
—
丹尼尔·罗森瓦瑟
@DanielRosenwasser 2.1.4
—
tony19
现在,我看到了WebStorm和TS游乐场抱怨的原因:我在使用箭头功能时提供的类型注释
—
tony19
this
。
我在这里提交了一个错误:github.com/Microsoft/TypeScript/issues/13768-随时跟踪它并表示赞许。
—
丹尼尔·罗森瓦瑟