Когда я включаю 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:
this.
