Sub topic 13
Distributive Conditional Types
This chapter assumes you can write generic functions and type aliases, you know union types, and you have seen a basic conditional type of the form T extends U ? X : Y. It covers what happens when the checked type is a union, how to control that behavior, and the errors that come from not knowing about it.
The Behavior in One Example
A conditional type that checks a type parameter does not always treat a union as one unit. Instead, it runs the check on each member of the union separately and combines the results into a new union. This is called distribution.
type ToArray<T> = T extends unknown ? T[] : never;
type Distributed = ToArray<string | number>; // string[] | number[]You might expect (string | number)[]. You get string[] | number[] because TypeScript evaluates the conditional once for string and once for number, then unions the two results.
The same type written without distribution gives the other answer:
type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type NotDistributed = ToArrayWhole<string | number>; // (string | number)[]The two aliases differ only in the checked position. Wrapping T in a tuple turns distribution off.
The Rule
A conditional type distributes when both of these are true:
- The type being checked, the part before
extends, is a bare type parameter. "Bare" (also called "naked") means it isTitself and notT[],[T],T | null, or any other type built fromT. - The type argument supplied for that parameter is a union.
When both hold, A | B extends U ? X : Y is evaluated as (A extends U ? X : Y) | (B extends U ? X : Y).
If the argument is not a union, there is only one member to check and the result is the same as without distribution. This is why distribution is easy to miss. It only shows when you pass a union.
flowchart TDThe block above is not a valid diagram block, so use the diagram below.
Practical Use: Filtering Unions
Distribution is useful because it lets a conditional type act as a filter. Returning never for a member removes it, since never disappears from any union.
type NonNullish<T> = T extends null | undefined ? never : T;
type Clean = NonNullish<string | number | null | undefined>; // string | numberEach member is checked alone. null and undefined map to never and vanish. string and number map to themselves. The built-in Exclude and Extract utility types work this way:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type Letters = "a" | "b" | "c";
type WithoutA = MyExclude<Letters, "a">; // "b" | "c"
type OnlyAB = MyExtract<Letters, "a" | "b">; // "a" | "b"If MyExclude did not distribute, Letters extends "a" would be false for the whole union and the result would be all of Letters. Nothing would be excluded.
Distribution also combines with infer to transform each member:
type ElementType<T> = T extends (infer U)[] ? U : T;
type Mixed = ElementType<string[] | number[] | boolean>; // string | number | booleanHere string[] gives string, number[] gives number, and boolean is not an array so it stays. Note that boolean is itself the union true | false, and it distributes too. The result is the same, so you do not notice.
Turning Distribution Off
Sometimes you want to ask a question about the union as a whole. Wrap both sides of extends in a one-element tuple:
type IsUnion<T> = [T] extends [string] ? "all strings" : "not all strings";
type A = IsUnion<"x" | "y">; // "all strings"
type B = IsUnion<"x" | 1>; // "not all strings"Because [T] is not a bare type parameter, TypeScript treats T as one type. The check ["x" | 1] extends [string] fails as a whole.
Compare with the distributive version:
type IsStringDist<T> = T extends string ? "yes" : "no";
type C = IsStringDist<"x" | 1>; // "yes" | "no"The result is a union of both answers, which is rarely what you want when you are asking one yes-or-no question.
| Form | Distributes? | `Check<string \ | number>` result for `X extends string ? 1 : 2` |
|---|---|---|---|
| `T extends string ? 1 : 2` | Yes | `1 \ | 2` |
| `[T] extends [string] ? 1 : 2` | No | `2` | |
| `T[] extends string[] ? 1 : 2` | No | `2` |
The `never` Edge Case
The type never is the empty union, a union with zero members. A distributive conditional type applied to never has nothing to iterate over, so the result is never, not either branch.
type IsString<T> = T extends string ? true : false;
type D = IsString<never>; // never, not falseThis surprises people who write a check like IsString<T> and pass in a value that turned out to be never. If you want never to produce a real answer, disable distribution:
type IsStringStrict<T> = [T] extends [string] ? true : false;
type E = IsStringStrict<never>; // trueHere [never] extends [string] is true, because never is assignable to everything. Decide which behavior you need. For a boolean check that must always return true or false, the tuple form is safer.
Distribution Is Not Limited to Aliases You Wrote
Any conditional type with a naked type parameter distributes, including ones inside object types and function return types.
type Wrap<T> = { value: T extends string ? "text" : "other" };
type W = Wrap<string | number>;
// { value: "text" | "other" }Here the conditional sits inside a property, and it still distributes over T. The object is not duplicated. The union appears in the property type.
If you need the object itself to be a union, the conditional must be at the top level:
type WrapEach<T> = T extends string ? { value: "text" } : { value: "other" };
type W2 = WrapEach<string | number>;
// { value: "text" } | { value: "other" }Distribution Needs a Type Parameter
Distribution happens on a type parameter, not on a type alias you pass in. If you write the union directly in a conditional, nothing distributes:
type Direct = string | number extends string ? "yes" : "no"; // "no"There is no parameter here, so the union is checked as one type. Distribution only applies after you substitute a union into a parameter that was declared with the conditional.
A related trap is using an intermediate type parameter. If you alias the parameter before checking it, the check still sees a type parameter and distributes. If you instead check T[keyof T] or Array<T>, it does not, because those are not bare parameters.
Common Mistakes
- Expecting one answer from a union.
IsStringDist<string | number>returns"yes" | "no". If you want a single boolean, wrap in a tuple. - Forgetting
never. A distributive check onnevergivesnever. Use[T] extends [U]whennevermust give a real result. - Wrapping accidentally. Writing
T[] extends U[]orT | undefined extends Uquietly turns distribution off. Results then differ from what you saw in tests with single types. - Assuming object types split. A conditional inside a property does not split the containing object. Move the conditional to the top level of the alias.
- Testing only with non-union arguments. Distribution is invisible until a union arrives, so always test generic conditional types with a union and with
never.
A Worked Example: Event Handlers
Suppose you model events as a union and want to get the payload of one named event.
type AppEvent =
| { type: "click"; x: number; y: number }
| { type: "key"; code: string }
| { type: "close" };
type PayloadOf<E, Name extends string> =
E extends { type: Name } ? Omit<E, "type"> : never;
type ClickPayload = PayloadOf<AppEvent, "click">;
// { x: number; y: number }
type KeyPayload = PayloadOf<AppEvent, "key">;
// { code: string }E is a bare parameter and AppEvent is a union, so each member is tested. Only the member whose type matches survives. The others become never and drop out. Without distribution, AppEvent extends { type: "click" } would be false and the result would be never.
Exercise
Given type Pick1<T> = T extends string ? T : never;, what is Pick1<"a" | 1 | "b">, and how would you change the definition so that Pick1<"a" | 1> returns never because the union as a whole is not a string?
Show answer
The result is "a" | "b". Each member is checked separately, 1 becomes never, and the rest stay. To check the union as a whole, write type Pick1<T> = [T] extends [string] ? T : never;. Then "a" | 1 does not extend string, so the result is never.
Exercise
What does IsString<never> return for type IsString<T> = T extends string ? true : false;, and why?
Show answer
It returns never. never is a union with no members, so the distributive conditional has nothing to evaluate and produces an empty union. Using [T] extends [string] ? true : false would return true instead.