infer
声明一个类型变量并对它进行使用,可以用于函数类型的参数/返回值Partial<T>
将某个类型的属性全部变为可选项Required<T>
将某个类型的属性全部变为必选Readonly<T>
将某个类型的属性全部变为只读Record<K extends keyof any, T>
将 K 中所有的属性的值转换为 T 类型Pick<T, K extends keyof T>
将类型 T 中的子属性挑出来,变成包含这个类型部分属性的子类型Omit<T, K extends keyof any>
将类型 T 中的子属性中属于 K 的部分 挑出来,变成不包含这个类型部分属性的子类型Exclude<T, U>
将类型 T 中属于类型 U 的属性移除Extract<T, U>
将类型 T 中属于类型 U 的属性挑选出来NonNullable<T>
过滤掉类型 T 中的 null 和 undefined 类型ReturnType<T>
的作用是用于获取函数 T 的返回类型。InstanceType<T>
的作用是获取构造函数类型的实例类型。ThisType<T>
的作用是用于指定上下文对象的类型。Parameters<T>
的作用是用于获得函数的参数类型组成的元组类型。ConstructorParameters<T>
的作用是用于获得构造函数的参数类型组成的元组类型。(如果 T 不是函数,则返回的是 never 类型)。
infer
使用示例:
1 | type FunctionReturnType<T> = T extends (...args: any[]) => infer R ? R : any; |
infer R
表示符合函数类型的返回值- 这里使用了 TS 的条件语法,如果 T 和
(...args:any[]) => ...
类型,那么FunctionReturnType<T>
类型就是 T 的返回值类型,否则就是any
Partial
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
使用示例:
1 | interface Todo { |
Required
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
Record
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | interface PageInfo { |
Pick
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | interface Todo { |
Omit
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | interface Todo { |
Exclude
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | type T0 = Exclude<"a" | "b" | "c", "a">; |
Extract
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | type T0 = Extract<"a" | "b" | "c", "a" | "c">; |
NonNullable
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | type T0 = NonNullable<string | number | undefined>; // string | number |
ReturnType
1 | 定义: |
示例:
1 | type T0 = ReturnType<() => string>; // string |
InstanceType
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | class C { |
ThisType
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
注意:使用 ThisType
时,必须确保 --noImplicitThis 标志设置为 true。
示例:
1 | interface Person { |
Parameters
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | type A = Parameters<() => void>; // [] |
ConstructorParameters
定义:
1 | // node_modules/typescript/lib/lib.es5.d.ts |
示例:
1 | type A = ConstructorParameters<ErrorConstructor>; // [(string | undefined)?] |
参考网站
- semlinker 全栈修仙之路 – 掌握 TS 这些工具类型,让你开发事半功倍