Awaited [promise, built-in]
假如我们有一个 Promise 对象,这个 Promise 对象会返回一个类型。在 TS 中,我们用 Promise 中的 T 来描述这个 Promise 返回的类型。请你实现一个类型,可以获取这个类型。
// 例如:Promise<ExampleType>,请你返回 ExampleType 类型。
type ExampleType = Promise<string>
type Result = MyAwaited<ExampleType> // string
/**
* 思路:
* 1. 先约束左边的类型 因为参数不知道是什么参数所以是 unknown
* 2. 然后校验右边传入的类型是否是 Promise
* 3. 使用 infer 来获取 Promise 参数的数据类型
* 4. 用 infer 获取到的 U 来判断是否是 Promise 类型 如果是则递归 MyAwaited 否则返回 U ,这样不管传入的是多少层 Promise 都能进行解析出来
*/
type MyAwaited<T extends Promise<unknown>> = T extends Promise<infer U>
? U extends Promise<unknown>
? MyAwaited<U>
: U
: never;