infer
infer关键字用于在类型表达式中声明局部变量,充当占位符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
type Type<T> = T extends Array<infer U>? U: T
type A = Type<string|number> type B = Type<(string|number)[]>
type Arr<T> = T extends Array<infer U>? U: never
type C = Arr<[string,number]> type D = Arr<string>
|
infer类型提取
提取头部元素
- 泛型T被约束为只能是数组类型
- 通过infer提取第一个元素的类型First,后面的元素则是任意类型
- 返回局部变量First
1 2 3 4 5 6
| type Arr = [1,1,4,5,1,4] type First<T extends any[]> = T extends [infer First,...any[]]? First: [] type a = First<Arr>
type Last<T extends any[]> = T extends [...any[],infer Last]? Last: []
|
剔除头部元素
- 泛型T被约束为只能是数组类型
- 第一个元素的类型不用管,通过infer提取剩余元素的类型Rest
- 返回局部变量Rest
1 2 3 4 5 6
| type Arr = [1,1,4,5,1,4] type First<T extends any[]> = T extends [unknown,...infer Rest]? Rest: [] type a = First<Arr>
type Last<T extends any[]> = T extends [...infer Rest,unknown]? Rest: []
|
infer递归
1 2 3 4
| type Arr = [1,2,3,4] type Reverse<T extends any[]> = T extends [infer First, ...infer rest]? [...Reverse<rest>, First]: T type Res = Reverse<Arr>
|