Quand je permets noImplicitThis
à tsconfig.json
, je reçois cette erreur pour le code suivant:
'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`
});
L'ajout d'un typé this
aux paramètres de rappel entraîne la même erreur:
foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
Une solution de contournement consiste à remplacer this
par l'objet:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
Mais quelle est la solution appropriée pour cette erreur?
MISE À JOUR: Il s'avère que l'ajout d'un tapé this
au rappel corrige en effet l'erreur. Je voyais l'erreur car j'utilisais une fonction de flèche avec une annotation de type pour this
:
this
.