【问题标题】:'this' implicitly has type 'any' because it does not have a type annotation'this' 隐含类型为 'any' 因为它没有类型注释
【发布时间】: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 - 随时跟踪它并竖起大拇指。

标签: typescript typescript2.0


【解决方案1】:

确实通过插入带有类型注释的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 issue 以改进编译器的错误消息并使用 this 和箭头函数突出显示实际的语法错误。

【讨论】:

    【解决方案2】:

    用于方法装饰器声明 配置"noImplicitAny": true, 您可以根据@tony19 的回答明确指定此变量的类型

    function logParameter(this:any, target: Object, propertyName: string) {
      //...
    }
    

    【讨论】:

      【解决方案3】:

      你可以添加

       "noImplicitAny": false,
      

      tsconfig.json
      

      正如here所说的那样

      【讨论】:

      • 禁用类型检查绝不是个好主意
      • 他没有禁用类型检查,他允许隐式 any 如果这是他拥有的所有代码,在这种情况下可能是可接受的边界。
      猜你喜欢
      • 2021-09-27
      • 2020-09-25
      • 2019-08-04
      • 2018-10-29
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      相关资源
      最近更新 更多