相关疑难解决方法(0)

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

当我启用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)

typescript typescript2.0

98
推荐指数
3
解决办法
6万
查看次数

标签 统计

typescript ×1

typescript2.0 ×1