Skip to the solution
MediumFrontend8 min read

What is the Awaited utility type?

199 views

The problem

Question presented to candidate: "What is the Awaited utility type? Why did TypeScript add it when T extends Promise<infer U> ? U : T already existed, and where do you use it?"

What a strong answer should cover:

  • Awaited<T> is the type you get from await on a T: it unwraps promises recursively, unwraps any thenable (an object with a callable then), and leaves non-promise types unchanged
  • It distributes over unions: Awaited<boolean | Promise<number>> is boolean | number
  • Common use: Awaited<ReturnType<typeof fn>> for the resolved value of an async function; library typings such as Promise.all use it so tuples keep each slot type
  • It was added in TypeScript 4.5; a one-level infer version leaves Promise<string> behind for nested promises
  • Generic code: await on a T gives Awaited<T>, and an inferred generic async return type can be wrong, so annotate Promise<Awaited<T>>

Code / implementation expected: Optional β€” Awaited<ReturnType<...>>, or a hand-written recursive version.

  • awaited

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptWhat Awaited unwraps, at compile time and at run time
TypeScriptA hand-written Awaited, edge cases and Awaited in generic code

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 60 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What do keyof and typeof do in TypeScript?

Continue