Skip to main content

Awaited

If we have a type which is wrapped type like Promise. How we can get a type which is inside the wrapped type?

For example: if we have Promise<ExampleType> how to get ExampleType?

ts
type ExampleType = Promise<string>
 
type Result = MyAwaited<ExampleType> // string
Cannot find name 'MyAwaited'. Did you mean 'Awaited'?2552Cannot find name 'MyAwaited'. Did you mean 'Awaited'?
ts
type ExampleType = Promise<string>
 
type Result = MyAwaited<ExampleType> // string
Cannot find name 'MyAwaited'. Did you mean 'Awaited'?2552Cannot find name 'MyAwaited'. Did you mean 'Awaited'?
Solution ✅
ts
type ExampleType = Promise<string>
type AnotherType = Promise<Promise<string>>
 
type MyAwaited<T> = T extends Promise<infer Inner> ? MyAwaited<Inner> : never
 
type Result = Awaited<ExampleType> // string
type NewResult = Awaited<AnotherType> // string
ts
type ExampleType = Promise<string>
type AnotherType = Promise<Promise<string>>
 
type MyAwaited<T> = T extends Promise<infer Inner> ? MyAwaited<Inner> : never
 
type Result = Awaited<ExampleType> // string
type NewResult = Awaited<AnotherType> // string