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 章节中了解更多关于此类实用类型的信息。