TypeScript 对象类型
TypeScript 有用于输入对象的特定语法。
参阅:JavaScript 对象。
实例
const car: { type: string, model: string, year: number } = { type: "Toyota", model: "Corolla", year: 2009 };
像这样的对象类型也可以单独编写,甚至可以重用,更多细节请查看接口。
类型推断
TypeScript 可以根据属性的值推断其类型。
实例
const car = { type: "Toyota", }; car.type = "Ford"; // no error 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 实用类型。