Коли я включаю 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
.