TypeScript 对象类型
TypeScript 有一个用于输入对象的特定语法。
可以访问本站的 JavaScript 对象章节 学习更多的 JS 对象知识。
const car: { type: string, model: string, year: number } = {
type: "Toyota",
model: "Corolla",
year: 2009
};
console.log(car);
对象类型 也可以单独编写,甚至可以重用,请查看 接口 以了解更多细节。
类型推断
TypeScript 可以根据属性的值推断属性的类型。
const car = {
type: "Toyota",
};
car.type = "Ford"; // no error
car.type = 2; // Error: Type 'number' is not assignable to type 'string'.
console.log(car);
可选属性
对象属性是不必在对象定义中定义的特性。
不使用可选属性的实例:
const car: { type: string, mileage: number } = { // Error: Property 'mileage' is missing in type '{ type: string; }' but required in type '{ type: string; mileage: number; }'.
type: "Toyota",
};
car.mileage = 2000;
使用可选属性的实例:
// no error on optional property, remove it and see what happens
const car: { type: string, mileage?: number } = {
type: "Toyota"
};
car.mileage = 2000;
console.log(car);
索引签名
索引签名可用于没有定义属性列表的对象。
const nameAgeMap: { [index: string]: number } = {};
nameAgeMap.Jack = 25; // no error
nameAgeMap.Mark = "Fifty"; // Error: Type 'string' is not assignable to type 'number'.
console.log(nameAgeMap);
像这样的索引签名也可以用诸如 Record<string,number>
之类的实用程序类型来表示。
可以访问本站的 TypeScript 实用程序类型 一章中了解更多关于此类实用程序类型的信息。