当我启用noImplicitThis
时tsconfig.json
,我得到以下代码的此错误:
Run Code Online (Sandbox Code Playgroud)'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`
});
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)