type Foo<T> = T extends {t: infer Test} ? Test: string type One = Foo<number> // string,因为number不是一个包含t的对象类型 type Two = Foo<{t: boolean}> // boolean,因为泛型参数匹配上了,使用了infer对应的type type Three = Foo<{a: number, t: () =>void}> // () => void,泛型定义是参数的子集,同样适配
infer用来对满足的泛型类型进行子类型的抽取,有很多高级的泛型工具也巧妙的使用了这个方法。
EXtract / Exclude
我们可能想要用在函数里面使用name属性,并透传剩下的属性:
1 2 3 4 5 6 7 8 9
type ExtractName = { name: string }
functionremoveName(props) { const {name, ...rest} = props; // do something with name... return rest: }
type MockRecords<K extends keyof any, T> = { [P in K]: T } type MockPick<T, K extends keyof T> = { [P in K]: T[P] } type MockReadonly<T> = { readonly [P in keyof T]: T[P] } type MockParital<T> = { [P in keyof T]?: T[P] }
type MockOmit<T, K extendsstring | number | symbol> = Pick<T, Exclude<keyof T, K>>
type MockExclude<T, U> = T extends U ? never : T type MockExtract<T, U> = T extends U ? T : never
type MockNonNullable<T> = T extendsnull | undefined ? never : T
函数相关的类型
Parameters 由函数类型的Type的参数类型类型构建一个元组类型
1 2
type FillParams = Parameters<typeofArray.prototype.fill> // type FillParams = Parameters<typeof Array.prototype.fill> type SomeParams = Parameters<typeofArray.prototype.reduce> // type SomeParams = [callbackfn: (previousValue: unknown, currentValue: any, currentIndex: number, array: any[]) => unknown, initialValue: unknown]
Parameters源码是
1 2
// 此处使用 infer P 将参数定为待推断类型 type Parameters<T extends (...arg: any) => any> = T extends (...args: infer P) => any ? P : never