'this'隐式具有类型'any',因为它没有类型注释


123

在中启用noImplicitThistsconfig.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游乐场抱怨的原因:我在使用箭头功能时提供的类型注释this
tony19

2
我在这里提交了一个错误:github.com/Microsoft/TypeScript/issues/13768-随时跟踪它并表示赞许。
丹尼尔·罗森瓦瑟

Answers:


139

通过插入this类型注释作为第一个回调参数,确实可以修复该错误。我试图通过同时将回调更改为箭头函数而失败:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

应该是这样的:

foo.on('error', function(this: Foo, err: any) {

或这个:

foo.on('error', function(this: typeof foo, err: any) {

创建了一个GitHub 问题来改善编译器的错误消息,并使用this和箭头功能突出显示实际的语法错误。


如果在构造函数中使用“ this”,则“ this”需要具有什么类型的注释?
BluE

@BluE假设正在引用成员属性/函数,this则将是正在初始化的类的类型。例如,如果constructor是为类MyClass,对于类型注释thisMyClass
tony19
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.