で有効にするnoImplicitThis
とtsconfig.json
、次のコードでこのエラーが発生します。
'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またはナイトリーバージョンでこれを試しましたか?
—
Daniel Rosenwasser 2017年
@DanielRosenwasser 2.1.4
—
tony19
そして、WebStormとTSプレイグラウンドが不平を言っている理由がわかり
—
tony19 2017年
this
ます。