【发布时间】:2017-06-16 03:02:03
【问题描述】:
当我在tsconfig.json 中启用noImplicitThis 时,我收到以下代码的错误:
'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 还是 nightly 版本上试过这个?
-
@DanielRosenwasser 2.1.4
-
我现在明白了 WebStorm 和 TS Playground 抱怨的原因:我在为
this提供类型注释的同时使用了箭头函数。 -
我在这里提交了一个错误:github.com/Microsoft/TypeScript/issues/13768 - 随时跟踪它并竖起大拇指。