Skip to the solution
HardFrontend10 min read

What are conditional types?

234 views

The problem

Question presented to candidate: "What is a conditional type in TypeScript? Write one, explain what extends means inside it, and tell me where you have seen them used."

What a strong answer should cover:

  • The form T extends U ? X : Y: a type-level if/else that picks X when T is assignable to U, otherwise Y; added in TypeScript 2.8
  • extends means assignability, not equality: literals fit their wide type, objects with extra properties fit, any gives both branches, the first match in a chain wins
  • Deferred resolution: inside a generic function the condition is unresolved, so returning a concrete value needs a cast (or overloads)
  • infer to pull a type out of a pattern (T extends (infer E)[] ? E : T), and that the standard Exclude, Extract and ReturnType are conditional types (NonNullable started as one in 2.8 but is T & {} in today's lib)
  • When the checked type is a naked type parameter the condition distributes over unions (its own topic), and never then gives never
  • Trade-off against function overloads for return types that depend on arguments

Code / implementation expected: Yes β€” a small conditional type such as TypeName<T> or a return type that depends on an argument.

  • conditional-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.

TypeScriptConditional types, deferral and infer
TypeScriptWhat extends means: assignability edge cases

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 80 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

How do you choose between `NoInfer<T>`, `satisfies`, and `const` type params when designing APIs?

Continue