การแปลงประเภท - อินเทอร์เฟซ TypeScript เป็นประเภทค่าที่ส่งกลับของฟังก์ชัน
ฉันจำเป็นต้องใช้ interface ของ Typescript เป็นชนิดของค่าที่ฟังก์ชันส่งกลับ interface คือ
interface IPerson {
name: string,
age: number
}
ถ้าฉันกำหนดวัตถุให้กับมัน มันจะตรวจสอบประเภทและปฏิเสธถ้าไม่ตรงกัน เช่น
const person: IPerson = { name: 'Tom', age: '26' };
แต่ถ้าฉันใช้มันเป็นประเภทที่ส่งค่ากลับของฟังก์ชัน ดูเหมือนว่ามันจะไม่ตรวจสอบประเภท
const personJSON = '{ "name": "Jack", "age": "30"}';
const getPersonFromJSON = <IPerson>(json) : IPerson => {
return JSON.parse(json);
}
console.log(getPersonFromJSON(personJSON));
ดูเหมือนว่าค่าที่ส่งกลับจะรับอายุเป็นสตริง
{ name: 'Jack', age: '30' }
สงสัยว่าฉันทำพลาดอะไร ขอบคุณมาก
คำตอบ #1
const getPersonFromJSON = <IPerson>(json) : IPerson => {
return JSON.parse(json);
}
นี่เหมือนกับ
const getPersonFromJSON = <T>(json) : T => {
return JSON.parse(json);
}
และกำหนดฟังก์ชันทั่วไป ดังนั้นในทางปฏิบัติมันคือ <any>(json: any): any
คุณควรประกาศมันเป็น
const getPersonFromJSON = (json) : IPerson => {
return JSON.parse(json);
}
แทน
เอกสารอ้างอิง:
- https://www.typescriptlang.org/docs/handbook/2/generics.html
