Skip to the solution
HardFrontend10 min read

How do you use infer to build deep Awaited, ReturnType and Unwrap utilities?

709 views

The problem

Question presented to candidate: "Using infer, build me a deep version of Awaited, a ReturnType that sees through curried functions, and a general Unwrap that peels promises, arrays and functions. Then tell me where these break."

What a strong answer should cover:

  • The recipe: a conditional type whose true branch calls itself on the inferred part (T extends PromiseLike<infer V> ? DeepAwaited<V> : T), with the false branch as the base case
  • Ordering several infer checks in one chain (promise, then array, then function) and choosing what non-matching types return
  • Distribution: a naked T unwraps each union member separately; [T] extends [...] tests the union as a whole
  • Practical use: mapping an API client to its resolved data with Awaited<ReturnType<...>>, and typing arguments with infer P
  • Limits: deep unwraps are greedy, special inputs (any, never, unknown), and the instantiation depth limit (error TS2589); tail-recursive conditional types (TypeScript 4.5) go much deeper

Clarifying questions expected:

  • Should Unwrap stop at arrays and functions, or only peel promises?
  • Should a union be unwrapped member by member, or treated as one type?

Code / implementation expected: Yes β€” write the recursive utilities and show them on nested input.

  • infer
  • utility-types

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

10 min read Β· 11 sections

Run the code

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

TypeScriptDeep Awaited, FinalReturn, Unwrap and distribution
TypeScriptTyping an API client with ApiData and Args

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 69 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 nextHard

What does `NoInfer<T>` do and when should you block inference?

Continue