索引访问类型

我们可以使用索引访问类型来查找另一个类型上的特定属性

ts
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
type Age = number
Try

索引类型本身也是一种类型,因此我们可以使用联合、keyof 或其他类型

ts
type I1 = Person["age" | "name"];
type I1 = string | number
 
type I2 = Person[keyof Person];
type I2 = string | number | boolean
 
type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];
type I3 = string | boolean
Try

如果你尝试索引一个不存在的属性,你甚至会看到错误

ts
type I1 = Person["alve"];
Property 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.
Try

索引使用任意类型的另一个示例是使用number 获取数组元素的类型。我们可以将它与typeof 结合起来,方便地捕获数组字面量的元素类型

ts
const MyArray = [
{ name: "Alice", age: 15 },
{ name: "Bob", age: 23 },
{ name: "Eve", age: 38 },
];
 
type Person = typeof MyArray[number];
type Person = { name: string; age: number; }
type Age = typeof MyArray[number]["age"];
type Age = number
// Or
type Age2 = Person["age"];
type Age2 = number
Try

你只能在索引时使用类型,这意味着你不能使用const 来创建变量引用

ts
const key = "age";
type Age = Person[key];
Type 'key' cannot be used as an index type.
'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?
2538
2749
Type 'key' cannot be used as an index type.
'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?
Try

但是,你可以使用类型别名来实现类似的重构风格

ts
type key = "age";
type Age = Person[key];
Try

TypeScript 文档是一个开源项目。帮助我们改进这些页面 通过发送 Pull Request

此页面的贡献者
OTOrta Therox (5)

上次更新时间:2024 年 3 月 21 日