Когда я включаю 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');
});
Но каково правильное исправление этой ошибки?
UPDATE: Оказывается, добавление типизированного this к обратному обращению действительно устраняет ошибку. Я видел ошибку, потому что я использовал функцию стрелки с аннотацией типа для this:
