类型转换是TS最好玩也是语言的灵魂,想玩好需要熟练各种手段和工具,下面一一介绍类型转换的一些常用手段。
索引访问类型
我们可以使用索引访问类型查找其他类型的特定属性:
代码语言:javascript复制type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
//type Age = number
类型的索引访问类型,我们可以使用联合类型,keyof 或者 其他type:
代码语言:javascript复制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
如果index属性不存在的话,TS会报错
代码语言:javascript复制type I1 = Person["alve"];
//Property 'alve' does not exist on type 'Person'.
使用任意类型进行索引的另一个示例是使用number获取数组元素的类型。我们可以将其与typeof相结合,方便地捕获数组文本的元素类型:
代码语言:javascript复制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
索引是了个类型,我不能用变量去代替。
代码语言:javascript复制const key = "age";
type Age = Person[key];
//Type 'any' 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'?
当然你也可以这么写:
代码语言:javascript复制type key = "age";
type Age = Person[key];