索引访问类型

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

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
// 或者
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

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request

Contributors to this page:
  (6)

Last updated: 2024年10月10日