Sub topic 6
Distribution over unions
This chapter assumes you know basic conditional types (T extends U ? X : Y), generics with type parameters, and union types. You should also be comfortable reading never and unknown.
The working model
A conditional type checks one type against a constraint and picks a branch. When the type being checked is a naked type parameter, TypeScript runs the check once for each member of a union and then joins the results. This is called distribution.
type ToArray<T> = T extends unknown ? T[] : never;
type Distributed = ToArray<string | number>;
// string[] | number[]
const d: Distributed = ["hello"]; // OKRead the steps this way. TypeScript takes string | number and splits it into two checks: string extends unknown ? string[] : never, which gives string[], and number extends unknown ? number[] : never, which gives number[]. The results join into string[] | number[].
Distribution only happens when the checked type is a naked type parameter. T extends ... distributes. [T] extends [...] and Foo<T> extends ... do not.
Turning distribution off
Wrap both sides in a tuple to check the whole union at once.
type ToArray<T> = T extends unknown ? T[] : never;
type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type Distributed = ToArray<string | number>;
// string[] | number[]
type Whole = ToArrayWhole<string | number>;
// (string | number)[]
const d: Distributed = ["hello"]; // OK
const w: Whole = ["hello", 1]; // OKUse the tuple form when you want a single answer for the entire union, such as asking whether a union as a whole is assignable to a type.
Common errors
Expecting a union result to behave like one value. With IsString<T> = T extends string ? true : false, IsString<string | number> gives boolean, not false. Each member contributes its own branch, so you get true | false.
Distributing over never. A distributive conditional over never returns never, because a union with no members has no branches to join. If a helper unexpectedly returns never, check whether its input was never.
Forgetting that boolean is a union. boolean is true | false, so a distributive conditional runs twice on it. Passing boolean to ToArray gives true[] | false[].
Using the wrong form in recursive helpers. A recursive type that needs to see the whole union at each step can loop or give unexpected results when distribution applies at every level. Test each level with a small input before you rely on it.
> Keep one rule in mind: distribution is the default for naked type parameters, and tuple wrapping is the way out.
Exercise
Exercise
What does ToArrayWhole<string | number> produce, and why does it differ from ToArray<string | number>?
Show answer
It produces (string | number)[]. ToArrayWhole wraps both sides in a tuple, so TypeScript checks the whole union once instead of distributing over each member. ToArray distributes, so it produces string[] | number[].