How infer keyword works
Daisho Komiyama edited this page Mar 3, 2024
·
1 revision
/**
* If the type `P` passed in is some kind of `PromiseLike<T>`
* (where `T` is a new type param), extract `T` and return it.
* If `P` is not some subtype of `PromiseLike<any>`, pass the
* type `P` straight through and return it
*/
type UnwrapPromise<P> = P extends PromiseLike<infer T> ? T : P;
type Test1 = UnwrapPromise<Promise<string>>
// ^ type Test1 = string
type Test2 = UnwrapPromise<Promise<[string[], number[]]>>
// ^ type Test2 = [string[], number[]]
type Test3 = UnwrapPromise<number>
// ^ type Test3 = number