TypeScript Reference ยท Type Operators
TypeScript conditional types
Reference for conditional types in TypeScript: the extends ? : syntax, distribution over unions, deferred evaluation, never, chaining and common patterns.
A conditional type chooses between two types depending on a relationship. T extends U ? X : Y means: if T is assignable to U, the result is X; otherwise it is Y. It is the type-level if.
On its own it looks like a curiosity, but combined with generics it powers most utility types (NonNullable, Exclude, Extract, ReturnType). The check happens when the type is instantiated, so the result depends on the argument you pass.
type IsString<T> = T extends string ? "yes" : "no"; type A = IsString<"hi">; // "yes" type B = IsString<42>; // "no"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Name<T> = T extends Condition ? WhenTrue : WhenFalse;
| Part | Description |
|---|---|
T extends Condition |
Assignability test. Condition can use infer to capture pieces of T. |
WhenTrue |
Result when T is assignable to Condition. May use the inferred names. |
WhenFalse |
Result otherwise. May be another conditional, forming a chain. |
Edge cases:
- If
Tis a bare type parameter and receives a union, the conditional distributes; see distributive conditional types. - If
Tisnever, a distributive conditional returnsnever. - While
Tis still a generic parameter inside a function body, the conditional is deferred: the compiler cannot decide which branch applies, so you usually need an assertion (as Measure<U>) when returning a value. anyas the checked type produces the union of both branches.
Usage notes
- Wrap in a tuple to stop distribution:
[T] extends [U] ? X : Y. - Chaining gives a type-level
else if, but deep chains are hard to read; prefer mapping through a lookup type when you have many cases. - Constraints do not narrow inside branches. To use a property of
Tin the true branch, intersect or useinfer. - Recursive conditionals can walk nested structures (deep readonly, flattening), with a compiler recursion limit.
- Return types of generic functions with conditional types are a common source of needing
as; keep implementations simple and the exposed signature precise, or use overloads. - Version note:
infer ... extendsconstraints arrived in TypeScript 4.7. - No runtime effect; all of this is erased.