ประเภทวัตถุทั่วไปใน TypeScript
ใน TypeScript มีวิธีใดบ้างในการกำหนดตัวแปรให้เป็นประเภทออบเจ็กต์ทั่วไป นี่คือสิ่งที่ฉันหมายถึงด้วย 'ประเภทออบเจ็กต์ทั่วไป'
let myVariable: GenericObject = 1 // Should throw an error
= 'abc' // Should throw an error
= {} // OK
= {name: 'qwerty'} //OK
เช่น ควรอนุญาตเฉพาะวัตถุ JavaScript ให้กำหนดค่าให้ตัวแปรเท่านั้น และไม่อนุญาตให้ประเภทข้อมูลอื่น (ตัวเลข สตริง บูลีน)
คำตอบ #1
แน่นอน:
type GenericObject = { [key: string]: any };
let myVariable1: GenericObject = 1; // Type 'number' is not assignable to type '{ [key: string]: any; }'
let myVariable2: GenericObject = 'abc'; // Type 'string' is not assignable to type '{ [key: string]: any; }'
let myVariable3: GenericObject = {} // OK
let myVariable4: GenericObject = {name: 'qwerty'} //OK
(โค้ดในสนามเด็กเล่น)
คำตอบ #2
Typescript 2.1+ ยังมีประเภทยูทิลิตี้, Record<K, T>, ที่คุณสามารถใช้แทนการสร้างคำจำกัดความของคุณเอง
const myObj: Record<string, any>;
ฉันชอบใช้สไตล์ที่อธิบายในคำตอบด้านบนเมื่อฉันสามารถให้ชื่อที่มีความหมายกับ key แต่ถ้าไม่ชัดเจนหรือจำเป็นจริง ๆ Record เป็นตัวเลือกที่ดี
