TypeScript Reference ยท Type Operators
Distributive conditional types in TypeScript
Reference for distributive conditional types in TypeScript: how unions spread over T extends U, why never disappears, and how to opt out with a tuple wrapper.
When the type being checked in a conditional type is a naked type parameter (written exactly as T extends ...) and you pass a union, TypeScript does not test the union as a whole. It runs the conditional once for each member and unions the results. This is distribution.
It is the reason Exclude<"a" | "b" | "c", "a"> is "b" | "c" and why NonNullable<string | null> is string. Distribution is automatic and almost always what you want, but it surprises people when the checked type is never or when they need to treat the union as one unit.
type ToArray<T> = T extends unknown ? T[] : never; type R = ToArray<string | number>; // string[] | number[]
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 Dist<T> = T extends U ? X : Y; // distributes over a union T type Whole<T> = [T] extends [U] ? X : Y; // does not distribute
| Condition | Result |
|---|---|
T is a naked type parameter and gets A | B |
(A extends U ? X : Y) | (B extends U ? X : Y) |
T is never |
never (zero members, zero results) |
T is wrapped ([T], T[], Promise<T>, T & {}) |
Tested as a single type |
T is boolean |
Distributes as true | false |
Usage notes
booleanis a union (true | false), soToArray<boolean>istrue[] | false[].neversurprises:IsNever<never>written naively returnsnever. Use[T] extends [never].- Intent in the checked position: if you write
T extends unknown ? ... : neveronly to force distribution, a short comment helps readers. - Only the checked type distributes. In
U extends T ? ...whereTis a parameter, nothing is distributed overT. - Inside the branches the type parameter refers to the individual member, not the whole union. To refer to the original union keep a second parameter with a default (
T, All = T). - Type aliases created with
inferalso distribute over the outer union. - Performance: big unions times big conditionals are expensive; wrap with
[T]when you do not need per-member results. - Compile-time only.