type A = ['ji','ni','tai','mei']
type Reverse<Arr extends unknown[]> =
Arr extends [...infer Rest,infer Last] ? [Last, ...Reverse<Rest>] : Arr
type Result = Reverse<A> // ['mei','tai','ni','ji']
-
infer
可以理解为引用
,也可以理解为声明变量
,通常出现在条件类型
,与 extends
一起使用
- 实践:
- 元祖体操:
模式匹配
和infer
// 元祖扩展
type A = [1]
type B = [...A,2]
// 取元祖的最后一个元素,这种方式也叫 模式匹配
type A = ['ji','ni','tai','mei']
type Last<T extends unknown[]> = T extends [...infer _ , infer L] ? L : never
type Result = Last<A> // 'mei'
- 字符串体操
// 内置 Capitalize;Uppercase;Lowercase;Uncapitalize
// 模版字符串类型
type S = 'ji'
type R = `${S}` // 'ji'
// 取第一个字符,模式匹配
type S = "ji ni tai mei"
type First<T extends string> = T extends `${infer F} ${string}` ? F : never
type Result = First<S>
// 取最后一个单词
type S = "ji ni tai mei"
type LastWord<T extends string> = T extends `${infer F} ${infer L}` ? LastWord<L> : T
type Result = LastWord<S> // 'mei'
// 取最后一个字符
type S = "ji ni tai mei !"
type LastOfTuple<T extends unknown[]> = T extends [...infer Rest, infer F] ? F : never
type StringToTuple<T extends string> =
T extends `${infer F}${infer Rest}` ? [F, ...StringToTuple<Rest>] : []
type LastOfString = LastOfTuple<StringToTuple<S>> // '!'
// string 转 联合类型
type StringToUnion<T extends string> =
T extends `${infer F}${infer R}` ? F | StringToUnion<R> : never
type C = StringToUnion<'abc'> // 'a' | 'b' | 'c'
- 函数常用工具类型:
ReturnType
、Parameters(返回一个元祖类型,因为参数是数组)
const fn = (a:number,b:number) => 'a + b'
const fn1 = ({name,age}: {name: string, age: number}) => {}
type F = typeof fn // (a:number, b:number) => string
type R = ReturnType<F> // string
type MyReturnType<T extends (...args:any)=>any> = T extends (...args:any)=> infer R ? R : any
type P = Parameters<F> // [a:number,b:number]
type P2 = Parameters<typeof fn1> // [{name:string, age:number}]