Sub topic 11
Distributive conditional types and how to turn distribution off
This chapter assumes you can write generic type aliases such as type Box<T> = { value: T }. It also assumes you know basic conditional types of the form T extends U ? X : Y, and you have read the earlier chapters on unions, intersections, and never. You do not need to know infer in depth, but one example uses it.
By the end you will be able to predict when a conditional type splits a union into pieces, explain why boolean and never behave oddly, and switch the behavior off when you need to.
A conditional type applied to a union
A conditional type chooses between two result types based on whether a type is assignable to another type.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"Now pass a union. You might expect string | number to be checked as one unit. A string | number is not assignable to string, so you would expect "no". That is not what happens.
type IsString<T> = T extends string ? "yes" : "no";
type C = IsString<string | number>; // "yes" | "no"The compiler checked string and number separately and combined the results into a union. This is called distribution. A conditional type is distributive when the type being checked is a naked type parameter. "Naked" means the parameter appears on its own to the left of extends, not wrapped in an array, tuple, function, or any other type.
The rule, step by step
When you instantiate T extends U ? X : Y with a union A | B | C for T, the compiler does this:
- It takes each member of the union on its own.
- It evaluates the conditional type once per member, with
Treplaced by that member. - It unions all the results.
So IsString<string | number> becomes IsString<string> | IsString<number>, which is "yes" | "no".
Why distribution is useful
Distribution is what makes the built-in utility types work on unions. Exclude is a one-line conditional type:
type MyExclude<T, U> = T extends U ? never : T;
type Remaining = MyExclude<"a" | "b" | "c", "a">; // "b" | "c"Each member is tested against "a". The member "a" becomes never, and never disappears from a union. The members "b" and "c" stay. Extract and NonNullable work the same way.
You can also use distribution to pick one member from a discriminated union by its tag:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
type ByKind<U, K extends string> = U extends { kind: K } ? U : never;
type Circle = ByKind<Shape, "circle">;
// { kind: "circle"; radius: number }Each shape is tested separately. Only the circle matches, so the square becomes never and vanishes.
Distribution also lets you work around the limits of keyof on unions. Recall that keyof (Cat | Dog) returns only the keys common to both members. A distributive helper returns every key from any member:
type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };
type CommonKeys = keyof (Cat | Dog); // "name"
type KeysOfUnion<T> = T extends unknown ? keyof T : never;
type AllKeys = KeysOfUnion<Cat | Dog>; // "name" | "meow" | "bark"The check T extends unknown is always true. Its only purpose is to force distribution. This is a common idiom, and you will see it in library code.
Turning distribution off
Sometimes you want to treat the union as one unit. Wrap both sides of extends in a one-element tuple. The checked type is then [T], which is not a naked type parameter, so the compiler does not split it.
type ToArray<T> = T extends unknown ? T[] : never;
type Distributed = ToArray<string | number>; // string[] | number[]
type ToArrayOfUnion<T> = [T] extends [unknown] ? T[] : never;
type NotDistributed = ToArrayOfUnion<string | number>; // (string | number)[]The first result is a union of two array types. The second is a single array whose elements may be either type. They are different types. A string[] is not assignable to (string | number)[] in the reverse direction, and you cannot push a number into a string[], so the choice matters.
Here is the same idea with a yes/no check:
type IsStringLoose<T> = T extends string ? "yes" : "no";
type IsStringStrict<T> = [T] extends [string] ? "yes" : "no";
type L1 = IsStringLoose<string | number>; // "yes" | "no"
type S1 = IsStringStrict<string | number>; // "no"
type S2 = IsStringStrict<"a" | "b">; // "yes"IsStringStrict asks whether the whole union is assignable to string. Only when every member is a string does the answer become "yes".
| Goal | Pattern | Result for `string \ | number` |
|---|---|---|---|
| Handle each member separately | `T extends U ? X : Y` | One result per member, unioned | |
| Handle the union as a whole | `[T] extends [U] ? X : Y` | One result for the entire union | |
| Force distribution without a real test | `T extends unknown ? F<T> : never` | `F<string> \ | F<number>` |
When distribution does not happen
Distribution depends on how the type is written, not on what it is. Three cases catch people.
The checked type is not a naked parameter. If you wrap the parameter, the union is checked whole:
type WrappedCheck<T> = T[] extends string[] ? "strings" : "other";
type W = WrappedCheck<string | number>; // "other"Here T[] is the checked type, so there is no distribution. The array (string | number)[] is not assignable to string[].
You write the union directly, not through a parameter. Distribution applies only to type parameters:
type Direct = (string | number) extends string ? "yes" : "no"; // "no"The distribution happens in a different place than you expected. The check applies to the parameter of the alias where the conditional type is written. If you write type Outer<T> = Inner<T> and Inner is distributive, then Outer<A | B> still distributes, because Inner receives the union as its argument. If Inner uses [T] extends [U], it does not.
Two special inputs: boolean and never
boolean is a union
boolean is defined as true | false. A distributive type therefore sees two members:
type Wrap<T> = T extends unknown ? T[] : never;
type W1 = Wrap<boolean>; // false[] | true[]This surprises people who expect boolean[]. If you want boolean[], use the non-distributive form [T] extends [unknown] ? T[] : never.
The same reasoning applies to enums. A union enum is a union of its member types, so a distributive conditional type runs once per enum member.
never is an empty union
never is a union with zero members. Distributing over zero members produces zero results, and an empty union of results is never. The conditional type never evaluates either branch.
type IsNeverBroken<T> = T extends never ? true : false;
type R1 = IsNeverBroken<never>; // never, not true
type IsNever<T> = [T] extends [never] ? true : false;
type R2 = IsNever<never>; // true
type R3 = IsNever<string>; // falseIsNeverBroken<never> is a classic bug. You expected true and got never. Wrapping both sides in a tuple makes the check run once on the whole input, so [never] extends [never] is true.
Distribution inside infer
infer extracts part of a type, and distribution applies to those checks too:
type ElementOf<T> = T extends (infer U)[] ? U : never;
type E1 = ElementOf<string[]>; // string
type E2 = ElementOf<string[] | number[]>; // string | number
type E3 = ElementOf<string[] | boolean>; // stringIn E3 the member boolean splits into true and false. Neither is an array, so both become never and drop out. Only the string[] member contributes.
If you wrote [T] extends [(infer U)[]] instead, string[] | number[] would still infer string | number. Inference over a whole union can behave differently when it cannot match every member, so test the result rather than assuming.
A worked example: splitting a union by a property
Suppose you have a union of events and want a handler map. Each handler receives only the event with a matching tag:
type AppEvent =
| { type: "click"; x: number; y: number }
| { type: "key"; code: string }
| { type: "scroll"; delta: number };
type EventOf<E, T extends string> = E extends { type: T } ? E : never;
type Handlers = {
[T in AppEvent["type"]]: (event: EventOf<AppEvent, T>) => void;
};
const handlers: Handlers = {
click: (e) => console.log(e.x, e.y),
key: (e) => console.log(e.code),
scroll: (e) => console.log(e.delta),
};EventOf is distributive, so it returns exactly one member for each tag. Inside click, the compiler knows e has x and y. If you add a fourth event to AppEvent, Handlers demands a fourth handler, which gives you an exhaustiveness check similar to the never trick from earlier in this tutorial.
Common errors
- Expecting a union to be tested as one unit.
T extends stringwithstring | numbergives"yes" | "no". Wrap in a tuple if you need a single answer. - Using a conditional type to test for
never. It returnsnever. Use[T] extends [never]. - Forgetting that
booleansplits. Results involvingbooleanappear astrueandfalsevariants. - Assuming a wrapped parameter still distributes.
T[] extends ...,keyof T extends ..., andPromise<T> extends ...do not distribute. - Assuming a concrete union distributes. It does not. Only type parameters do.
- Mixing up the result of a mapped type with distribution. Homomorphic mapped types such as
{ [K in keyof T]: ... }also distribute over unions whenTis a type parameter, but that is a separate mechanism from conditional types.
Exercise
Given type F<T> = T extends string ? T : never, what is F<"a" | 1 | "b">? Then rewrite F as G so that G<"a" | 1 | "b"> is never, and explain why the result changes.
Show answer
F<"a" | 1 | "b"> is "a" | "b". The type distributes: "a" stays, 1 becomes never, "b" stays. A non-distributive version is type G<T> = [T] extends [string] ? T : never. The whole union "a" | 1 | "b" is not assignable to string because 1 is not a string, so the false branch gives never.
Exercise
Write a type IsUnion<T> that is true when T is a union of two or more members and false otherwise, treating never as not a union. Hint: use a distributive helper to copy T, then compare the whole with each member.
Show answer
type IsUnion<T, U = T> = [T] extends [never] ? false : T extends unknown ? [U] extends [T] ? false : true : never; IsUnion<string | number> is true, IsUnion<string> is false, and IsUnion<never> is false. The default parameter U = T keeps a copy of the original union. The distributive check T extends unknown runs once per member, so inside it T is a single member while U is still the whole union. If U is assignable to that single member, the union has only one member, so the result is false. Otherwise it is true.