typescript - วิธีการกำหนดค่าตัวแปรให้กับประเภทที่มีคุณสมบัติเสริม?
นี่คือสไตล์ของฉัน:
export type Supply = {
id: number;
name: string;
manufacturer?: string;
model?: string;
}
นี่คือวิธีที่ฉันพยายามกำหนดค่าให้กับวัตถุที่มีประเภทนั้น:
return response['data']['supplies'].map((supply: ServerResponse.Supply) => {
let s = {
id: supply['supply_id'],
name: supply['name'],
}
if ('manufacturer' in supply) {
s.manufacturer = supply['manufacturer']
}
if ('model' in supply) {
s.model = supply['model']
}
return s;
});
ฉันได้รับการเตือนของ TypeScript:
[ts] คุณสมบัติ 'manufacturer' ไม่มีอยู่ในประเภท '{ id: number; name: string; }'.
[ts] คุณสมบัติ 'model' ไม่มีอยู่ในประเภท '{ id: number; name: string; }'
มีอะไรผิดพลาดกับโค้ดของฉันหรือ?
คำตอบ #1
แค่เพิ่มข้อมูลประเภท:
let s: Supply = {
id: supply['supply_id'],
name: supply['name'],
}
มิฉะนั้น TS จะสมมติว่าตัวแปรของคุณ s มีชนิดของตัวเองเป็น {id: number, name: string} ตามการประกาศเริ่มต้น
