TypeScript 物件型別
TypeScript 為物件型別定義了特定的語法。
請閱讀我們 JavaScript Objects 章節 中關於物件的更多內容。
示例
const car: { type: string, model: string, year: number } = {
type: "Toyota",
model: "Corolla",
year: 2009
};
自己動手試一試 »
像這樣的物件型別也可以分開編寫,甚至可以重複使用,有關更多詳細資訊,請檢視 介面。
型別推斷
TypeScript 可以根據屬性的值推斷出其型別。
示例
const car = {
type: "Toyota",
};
car.type = "Ford"; // 無錯誤
car.type = 2; // 錯誤:無法將型別“number”分配給型別“string”。
自己動手試一試 »
可選屬性
可選屬性是定義物件時不必必須包含的屬性。
沒有可選屬性的示例
const car: { type: string, mileage: number } = { // 錯誤:型別 “{ type: string; }” 中缺少屬性 “mileage”,但在型別 “{ type: string; mileage: number; }” 中是必需的。
type: "Toyota",
};
car.mileage = 2000;
帶有可選屬性的示例
const car: { type: string, mileage?: number } = { // 無錯誤
type: "Toyota"
};
car.mileage = 2000;
自己動手試一試 »
索引簽名
索引簽名可用於沒有定義屬性列表的物件。
示例
const nameAgeMap: { [index: string]: number } = {};
nameAgeMap.Jack = 25; // 無錯誤
nameAgeMap.Mark = "Fifty"; // 錯誤:無法將型別“string”分配給型別“number”。
自己動手試一試 »
像這樣的索引簽名也可以透過像 Record<string, number>
這樣的實用型別來表示。
在我們的 TypeScript Utility Types 章節中瞭解更多關於此類實用型別的資訊。