主题
模式匹配提取
通过 extends 对类型参数做匹配,结果保存到通过 infer 声明的局部类型变量里,如果匹配就能从该局部变量里拿到提取出的类型
数组类型
通过解构和Rest的配合,取想要的位置的类型
typescript
// First: 取数组第一个元素
type First<Arr extends unknown[]> =
Arr extends [infer P, ...unknown[]] ? P : never
字符串类型
通过模板字符串字面量类型提取字符串中想要的字符字面量
typescript
// Replace:声明要替换的字符串 Str、待替换的字符串 From、替换成的字符串 To
type Replace<
Str extends string,
From extends string,
To extends string
> = Str extends `${infer Prefix}${From}${infer Suffix}` ?
`${Prefix}${To}${Suffix}` : Str
type Test1 = Replace<'abc.py', 'py', 'html'> // abc.html
type Test2 = Replace<'abc.py', 'css', 'html'> // abc.py
函数
提取参数、返回值的类型
typescript
type Parameters<Fun extends Function> =
Fun extends (...args: infer Args) => unknown ? Args : never
type Return<Fun extends Function> =
Fun extends (...args: any[]) => infer Result ? Result : never
索引
提取某个索引的值的类型
typescript
// 模拟 react 中,提取对象 ref 的值得类型
type GetRefProps<Props> =
'ref' extends keyof Props
? Props extends { ref?: infer Value | undefined }
? Value
: never
: never
type Test1 = GetRefProps<{ ref: 'aaa' }> // 'aaa'
type Test2 = GetRefProps<{ ref: undefined }> // undefined
type Test3 = GetRefProps<{}> // never