เมื่อฉันเปิดใช้งาน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
:
คุณลองใช้ TypeScript 2.1 หรือเวอร์ชันกลางคืนหรือไม่?
—
Daniel Rosenwasser
@DanielRosenwasser 2.1.4
—
tony19
และตอนนี้ฉันเห็นเหตุผลที่ WebStorm และ TS playground บ่น: ฉันใช้ฟังก์ชันลูกศรในขณะที่ใส่คำอธิบายประกอบประเภทสำหรับ
—
tony19
this
.
ฉันยื่นข้อบกพร่องที่นี่: github.com/Microsoft/TypeScript/issues/13768 - อย่าลังเลที่จะติดตามและยกนิ้วให้
—
Daniel Rosenwasser