TypeScript 对象类型

TypeScript 有一个用于输入对象的特定语法。

可以访问本站的 JavaScript 对象章节 学习更多的 JS 对象知识。

  1. const car: { type: string, model: string, year: number } = {
  2. type: "Toyota",
  3. model: "Corolla",
  4. year: 2009
  5. };
  6. console.log(car);
对象类型 也可以单独编写,甚至可以重用,请查看 接口 以了解更多细节。

类型推断

TypeScript 可以根据属性的值推断属性的类型。

  1. const car = {
  2. type: "Toyota",
  3. };
  4. car.type = "Ford"; // no error
  5. car.type = 2; // Error: Type 'number' is not assignable to type 'string'.
  6. console.log(car);

可选属性

对象属性是不必在对象定义中定义的特性。

不使用可选属性的实例:

  1. const car: { type: string, mileage: number } = { // Error: Property 'mileage' is missing in type '{ type: string; }' but required in type '{ type: string; mileage: number; }'.
  2. type: "Toyota",
  3. };
  4. car.mileage = 2000;

使用可选属性的实例:

  1. // no error on optional property, remove it and see what happens
  2. const car: { type: string, mileage?: number } = {
  3. type: "Toyota"
  4. };
  5. car.mileage = 2000;
  6. console.log(car);

索引签名

索引签名可用于没有定义属性列表的对象。

  1. const nameAgeMap: { [index: string]: number } = {};
  2. nameAgeMap.Jack = 25; // no error
  3. nameAgeMap.Mark = "Fifty"; // Error: Type 'string' is not assignable to type 'number'.
  4. console.log(nameAgeMap);

像这样的索引签名也可以用诸如 Record<string,number> 之类的实用程序类型来表示。

可以访问本站的 TypeScript 实用程序类型 一章中了解更多关于此类实用程序类型的信息。