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

ton*_*y19 98 typescript typescript2.0

当我启用noImplicitThistsconfig.json,我得到以下代码的此错误:

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

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

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

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

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

但是这个错误的正确解决方法是什么?


更新:事实证明this,在回调中添加一个类型确实可以解决错误.我看到了错误,因为我正在使用带有类型注释的箭头函数this:

打字游乐场

ton*_*y19 105

通过this使用类型注释作为第一个回调参数插入,确实可以修复错误.我这样做的尝试是通过同时将回调更改为箭头函数来实现的:

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

应该是这样的:

foo.on('error', function(this: Foo, err: any) {
Run Code Online (Sandbox Code Playgroud)

或这个:

foo.on('error', function(this: typeof foo, err: any) {
Run Code Online (Sandbox Code Playgroud)

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


小智 21

在 tsconfig.json 中将“noImplicitAny”更改为 false 没有帮助。尝试"noImplicitThis": false在 tsconfig.json 中执行

  • 如果你的房子钥匙坏了,并不意味着你把锁拆了。`noImplicitAny` 是一个很好的启用规则。我认为当某些东西不起作用时建议将其切换为 false 并不是一个好主意。应该修复代码。 (15认同)
  • 它之所以有效,是因为您要关闭建议首先打开的 TypeScript 功能。 (3认同)

mus*_*una 11

对于带有配置的方法装饰器声明,"noImplicitAny": true, 您可以显式指定此变量的类型,具体取决于@tony19的答案

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}
Run Code Online (Sandbox Code Playgroud)