导航
×
   ❮   
HTML CSS JavaScript PHP Python C C++ Go Sass W3C Colors TypeScript ECMS

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


Copyright ©2026 蒙ICP备2026009383号 All Rights Reserved 提供的内容仅用于学习和测试,不保证内容的正确性。