Indexed Access Types 索引式访问类型
We can use an indexed access type to look up a specific property on another type: 我们可以使用索引式访问type来查找另一个type的特定属性
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
type Age = number
Try
The indexing type is itself a type, so we can use unions(联合类型), keyof, or other types entirely:
索引类型本身就是一种类型,因此我们可以使用联合类型, keyof或其他类型。
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
You’ll even see an error if you try to index a property that doesn’t exist:
如果你试图索引一个不存在的属性,你甚至会看到一个错误
type I1 = Person["alve"];
Property 'alve' does not exist on type 'Person'.Property 'alve' does not exist on type 'Person'.Try
Another example of indexing with an arbitrary type is using number to get the type of an array’s elements. We can combine this with typeof to conveniently capture the element type of an array literal:
使用任意类型进行索引的另一个示例是使用number获取数组元素的类型。我们可以将其与typeof相结合,以方便地捕获数组文字的元素类型
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
You can only use types when indexing, meaning you can’t use a const to make a variable reference:
您只能在索引时使用类型,这意味着您不能使用const进行变量引用
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'?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
However, you can use a type alias for a similar style of refactor:
但是,可以使用类型别名进行类似的重构
type key = "age";
type Age = Person[key];