Ketika saya mengaktifkan noImplicitThis
masuk tsconfig.json
, saya mendapatkan kesalahan ini untuk kode berikut:
'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`
});
Menambahkan yang diketik this
ke parameter callback menghasilkan kesalahan yang sama:
foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
Solusinya adalah mengganti this
dengan objek:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
Tapi apa perbaikan yang tepat untuk kesalahan ini?
UPDATE: Ternyata menambahkan yang diketik this
ke callback memang mengatasi kesalahan tersebut. Saya melihat kesalahan karena saya menggunakan fungsi panah dengan anotasi tipe untuk this
:
this
.