type A = Awaited<Promise<string>>; type A = string type B = Awaited<Promise<Promise<number>>>; type B = number type C = Awaited<boolean | Promise<number>>; type C = number | boolean
如果不考虑递归,可以利用 infer 实现一个简单的 Awaited
1 2 3 4
typeMyAwaited<T> = T extendsPromise<infer R> ? R : T;
type A = MyAwaited<Promise<string>>; // type A = string
Partial V2.1
将所有属性变为 可选 的,这个比较实用,尤其在复用一些 type/interface 的时候,
1 2 3 4 5 6 7 8 9 10 11 12 13
interfacePerson { name: string age: number address: string }
typeT4 = Parameters<any>; typeT4 = unknown[] typeT5 = Parameters<never>; typeT5 = never typeT6 = Parameters<string>; // Error Type 'string' does not satisfy the constraint '(...args: any) => any'. typeT6 = never typeT7 = Parameters<Function>; // Error Type 'Function' does not satisfy the constraint '(...args: any) => any'. // Error Type 'Function' provides no match for the signature '(...args: any): any'. typeT7 = never
ConstructorParameters
用来提取构造函数的参数,返回一个元组类型, 查看源码可以看到,有两个点需要注意:
abstract关键字修饰的函数叫抽象方法,而抽象方法只能出现在抽象类中
new (…args: any) => any,这就是对构造函数的定义
所以,这个工具类型只是针对抽象类发挥效果,never和any我们不需要关心。 平时基本很少用
1
typeConstructorParameters<T extendsabstractnew (...args: any) => any> = T extendsabstractnew (...args: infer P) => any ? P : never;
typeT7 = ReturnType<string>; // Error Type 'string' does not satisfy the constraint '(...args: any) => any'. l typeT7 = any
typeT8 = ReturnType<Function>; // Error Type 'Function' does not satisfy the constraint '(...args: any) => any'. // Error Type 'Function' provides no match for the signature '(...args: any): any'. typeT8 = any
classC { x = 0; y = 0; } typeT0 = InstanceType<typeof C>; typeT0 = C
typeT1 = InstanceType<any>; typeT1 = any
typeT2 = InstanceType<never>; typeT2 = never
typeT3 = InstanceType<string>; // Error Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'. typeT3 = any
typeT4 = InstanceType<Function>; // Error Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. // Error Type 'Function' provides no match for the signature 'new (...args: any): any'. typeT4 = any