typescript - วิธีการกำหนดชนิดเพื่อตรวจสอบว่าอ็อบเจ็กต์มีคีย์ id หรือไม่?
มีวิธีใดในการกำหนดอินเตอร์เฟซให้สามารถมีคีย์จำนวนเท่าใดก็ได้ แต่ต้องมีคีย์ id หรือไม่?
interface HasId{
id: number
}
บางสิ่งเช่นนี้สามารถกำหนดได้ แต่จะเกิดข้อผิดพลาดหากมีคีย์อื่นอยู่ในโครงสร้างข้อมูล
คำตอบ #1
ใช่ ในความเป็นจริงคุณจำเป็นต้องสร้างประเภท dictionary สามารถดูข้อมูลเพิ่มเติมเกี่ยวกับประเภทขั้นสูง
interface HasId {
id: number;
[key: string]: any;
}
คุณยังสามารถทำให้มันทั่วไปขึ้นได้เหมือน
interface IDictionary<T> {
[key: string]: T;
}
interface HasId extends IDictionary<number> {
id: number;
}
คำตอบ #2
ใช่ คุณสามารถใช้ชนิดแทรก (intersection type) กับชนิดเดิมของคุณและ Object มาตรฐานตัวอย่างเช่น:
interface HasId {
id: number;
}
type AtLeastHasId = HasId & {[key: string]: number};
const test1: AtLeastHasId = { // Property "id" is missing
};
const test2: AtLeastHasId = { // Fine
id: 123
};
const test3: AtLeastHasId = { // Fine
id: 123,
other: 456
};
ลิงก์สนามเด็กเล่น
