Sub topic 13
Distributive Conditional Types
Assume you know union types, generic type parameters, and basic conditional types. This chapter explains how a conditional type behaves when its checked type is a union.
A conditional type has the form T extends U ? X : Y. It chooses X when T is assignable to U; otherwise, it chooses Y. When T is a naked type parameter, TypeScript distributes the conditional type across each member of a union.
Distribution over unions
Consider this generic type:
type ToArray<T> = T extends unknown ? T[] : never;
type Result = ToArray<string | number>;
// string[] | number[]Because T is a naked type parameter, TypeScript evaluates the type once for each union member:
ToArray<string> | ToArray<number>The result is therefore:
string[] | number[]This is called distributive behavior. The conditional type distributes over the union in the same way that a function might process each item separately.
Distribution is useful when each union member needs its own transformed result. For example, a type can extract only certain members from a union:
type OnlyStrings<T> = T extends string ? T : never;
type Values = OnlyStrings<string | number | boolean>;
// stringThe number and boolean branches produce never. Since never represents an impossible type, it disappears from the resulting union.
Turning distribution off
Sometimes you want to test the entire union as one value. Wrap the type parameter in a tuple on both sides of extends:
type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type Result = ToArrayWhole<string | number>;
// (string | number)[]Now TypeScript does not see a naked T. It checks the complete union:
[string | number] extends [unknown]The result is one array whose elements may be strings or numbers. This differs from a union of separate array types:
| Type | Meaning | Column |
|---|---|---|
| `string[] | number[]` | The whole array is strings or the whole array is numbers |
| `(string \ | number)[]` | Each element may be a string or a number |
For example, this value matches (string | number)[] but not string[] | number[]:
const mixed: (string | number)[] = ["Ada", 42];Common uses and mistakes
Distributive conditional types often appear in utilities that filter, transform, or inspect union members. They are especially useful when defining reusable library types.
Remember these rules:
- A conditional type distributes when the checked side is a naked type parameter.
T extends unknown ? X : Yis often used to trigger distribution.- Wrapping
Tin a tuple, such as[T], prevents distribution. neverremoves a branch from the final union.- A union of arrays is different from an array containing a union.
Exercise
What is the result of type R = OnlyNumbers<string | number | boolean> when OnlyNumbers<T> = T extends number ? T : never?
Show answer
R is number. The string and boolean branches become never, which disappears from the union.