Skip to the solution
MediumFrontend11 min read

How do you type async functions and Promises?

783 views

The problem

Question presented to candidate: "How do you type async functions and Promises in TypeScript? Walk me through return types, errors, and running several promises at once โ€” and tell me which async bugs the compiler will not catch."

What a strong answer should cover:

  • An async function always returns Promise<T>: annotate Promise<User> (annotating User is error TS1064), Promise<void> when nothing useful is returned; plain returned values are wrapped
  • new Promise<T>(...) needs its type argument or the value is unknown; callback types say () => Promise<T>; Awaited and ReturnType derive types from existing async functions
  • Errors are untyped: Promise<T> has no error parameter, a catch (err) variable is unknown under strict (TypeScript 4.4+), but .catch and allSettled reasons are any
  • Concurrency: Promise.all on an array literal gives a typed tuple, allSettled results narrow on status, race with a Promise<never> timeout keeps the result type
  • Bugs tsc does not flag: async callbacks passed to forEach, floating promises, return without await inside try โ€” lint rules like no-floating-promises cover some of them

Clarifying questions expected:

  • Should independent calls run in parallel or one after another?
  • Is strict (or useUnknownInCatchVariables) on, and is type-aware linting part of the toolchain?

Code / implementation expected: Yes โ€” a typed async function with error handling, and a Promise.all or allSettled call.

  • async
  • promises

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

11 min read ยท 10 sections

Run the code

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

TypeScriptAsync return types, new Promise, Promise<void> and unknown errors
TypeScriptPromise.all tuples, allSettled, race and the forEach trap
TypeScriptError types in async code and return await inside try

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 31 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 does `arethetypeswrong` (attw) detect and how do you fix false ESM/CJS packages?

Continue