“this"隐式具有类型“any",因为它没有类型注释 [英] 'this' implicitly has type 'any' because it does not have a type annotation

查看:819
本文介绍了“this"隐式具有类型“any",因为它没有类型注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

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

class Foo 实现 EventEmitter {on(名称:字符串,fn:函数){}发出(名称:字符串){}}const foo = new Foo();foo.on('error', function(err: any) {控制台日志(错误);this.emit('end');//错误:`this` 隐式具有类型 `any`});

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

foo.on('error', (this: Foo, err: any) => {//错误:`this` 隐式具有类型 `any`

解决方法是将 this 替换为对象:

foo.on('error', (err: any) => {控制台日志(错误);foo.emit('end');});

但是此错误的正确修复方法是什么?

<小时>

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

解决方案

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

foo.on('error', (this: Foo, err: any) => {//不要这样做

应该是这样的:

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

或者这个:

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

<小时>

创建了 GitHub issue 以改进编译器的错误消息并突出显示实际语法this 和箭头函数出错.

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

'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 this to the callback parameters results in the same error:

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

A workaround is to replace this with the object:

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 this to the callback indeed addresses the error. I was seeing the error because I was using an arrow function with a type annotation for this:

解决方案

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

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 issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

这篇关于“this"隐式具有类型“any",因为它没有类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆