TS 索引访问类型
前端精髓
共 1135字,需浏览 3分钟
·
2023-01-07 00:11
我们可以使用索引访问类型来查找另一种类型的特定属性:
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
// type Age = number
索引类型本身就是一种类型,因此我们可以与联合类型、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
如果尝试索引不存在的属性,您会看到有报错:
type I1 = Person["alve"];
// Property 'alve' does not exist on type 'Person'.
使用数字获取数组元素的类型。我们可以将其与 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
我们只能使用类型进行索引,这意味着不能使用变量引用:
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 = "age";
type Age = Person[key];
评论