typescript “this”隐式具有类型“any”,因为它没有类型注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41944650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:33:59  来源:igfitidea点击:

'this' implicitly has type 'any' because it does not have a type annotation

typescripttypescript2.0

提问by tony19

When I enable noImplicitThisin tsconfig.json, I get this error for the following code:

当我启用noImplicitThisin 时tsconfig.json,我收到以下代码的错误:

'this' implicitly has type 'any' because it does not have a type annotation.
'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`
});

Adding a typed thisto the callback parameters results in the same error:

将 typed 添加this到回调参数会导致相同的错误:

foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`

A workaround is to replace thiswith the object:

解决方法是this用对象替换:

foo.on('error', (err: any) => {
  console.log(err);
  foo.emit('end');
});

But what is the proper fix for this error?

但是这个错误的正确修复是什么?



UPDATE:It turns out adding a typed thisto the callback indeed addresses the error. I was seeing the error because I was using an arrow function with a type annotation for this:

更新:事实证明,向this回调添加类型确实解决了错误。我看到错误是因为我使用了带有类型注释的箭头函数this

typescript playground

打字稿游乐场

回答by tony19

The error is indeed fixed by inserting thiswith a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

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

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

It should've been this:

应该是这样的:

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

or this:

或这个:

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


A GitHub issuewas created to improve the compiler's error message and highlight the actual grammar error with thisand arrow-functions.

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