前端必知必会-TypeScript 对象类型

文章目录

  • TypeScript 对象类型
    • 类型推断
    • 可选属性
    • 索引签名
  • 总结


TypeScript 对象类型

TypeScript 具有用于对对象进行类型化的特定语法。

示例

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 等实用程序类型来表示。


总结

本文介绍了TypeScript 对象类型的使用,如有问题欢迎私信和评论

你可能感兴趣的:(前端,typescript,ubuntu)