Awaited type under the hood in TypeScript

Example of Awaited use
1type Awaited<T> = any; // implementation
3type Step1 = Awaited<Promise<Promise<string | undefined>>>;
4type Step2 = Awaited<Promise<string | undefined>>;
5type Result = string | undefined;

Seventh challenge is Awaited

It's available since TypeScript 4.5 🔥🔥🔥

Like await in JavaScript, it unwraps Promise and gets the value in the same way.

Sometimes it's useful to get the value even if it's double wrapped with Promise so this is also possible.

Unboxing values from types

Type inference in conditional types is defined in TypeScript as following:

Within the extends clause of a conditional type, it is now possible to have infer declarations that introduce a type variable to be inferred. Such inferred type variables may be referenced in the true branch of the conditional type

Example of type inference in conditional types
1type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

As we want to unbox double or maybe thrice wrapped Promise we need Recursive Conditional Types:

Example of recursive conditional types
1type ElementType<T> = T extends ReadonlyArray<infer U> ? ElementType<U> : T;

It's available since TypeScript 4.1 and allows us to do so with Promise too:

1type Awaited<T> = T extends Promise<infer U> ? Awaited<U> : T;

This is it ⭐️

Don't forget to check the solution on Playground – 🚀

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter