Distributive conditional types

Advanced · 8 min

Why a conditional type applied to a union runs once per member, how `[T] extends [U]` turns that off, and why `never` in gives `never` out.

Before thisConditional typesUnion and literal types

Michigan TypeScript · 8 min

Distributive conditional types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Michigan TypeScriptReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • When a conditional type checks a naked type parameter and that parameter receives a union, the conditional runs once for each member and the results are joined back into a union.
  • Distribution is what lets a conditional filter a union: members that hit a `never` branch vanish from the result, which is exactly how `Exclude` and `Extract` work.
  • It only happens when the checked type is a bare type parameter such as `T`; `T[]`, `[T]` or `Promise<T>` on the left of `extends` are checked as a whole.
  • Wrapping both sides in one-element tuples, `[T] extends [U]`, is the standard way to switch distribution off and test the union as a single type.
  • `never` is the empty union, so distributing over it runs the conditional zero times and the result is `never`, whatever the branches say.
  • To test whether a type is `never`, write `[T] extends [never]`; the naked `T extends never` version returns `never` instead of `true`.
  • `boolean` is the union `true | false`, so it distributes too, which is why a naked conditional can turn `boolean` into `false[] | true[]`.

A result you didn’t ask for

Here is a conditional type that looks like it should wrap any type in an array:

type ToArray<T> = T extends unknown ? T[] : never;

type A1 = ToArray<string>; // string[]
type A2 = ToArray<string | number>; // string[] | number[]

The second result isn’t (string | number)[], an array that may mix strings and numbers. It’s string[] | number[], an array of only strings or an array of only numbers. Those are different types: [1, "a"] fits the first and not the second.

This is the behaviour the conditional types lesson hinted at when OnlyStrings filtered a union. It’s called distribution, and it’s on by default.

The rule

When a conditional type checks a naked type parameter, meaning a bare T on the left of extends, and T is given a union, TypeScript applies the conditional to each member of the union separately and then unions the results:

// ToArray<string | number>
//   = ToArray<string> | ToArray<number>
//   = string[] | number[]

Think of a mail sorter. A naked conditional doesn’t inspect the sack. It opens it and runs each letter through the machine on its own, then puts all the outputs in a new sack. Usually that’s exactly what you want, because most type-level questions are naturally per member.

Why it’s the default: filtering

Distribution is what makes conditional types useful on unions. Combine it with never, which vanishes from any union, and you get a filter. The built-in Exclude and Extract from the utility types lesson are defined like this:

type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;

type Status = "idle" | "loading" | "success" | "error";

type Done = MyExtract<Status, "success" | "error">; // "success" | "error"
type Pending = MyExclude<Status, "success" | "error">; // "idle" | "loading"

For Pending, each of the four members goes through T extends U ? never : T on its own. "success" and "error" turn into never, the other two pass through, and the nevers drop out of the final union.

What counts as naked

Only the bare type parameter distributes. Put anything around it and the check sees the whole union at once:

type Naked<T> = T extends string ? "yes" : "no";
type Wrapped<T> = T[] extends string[] ? "yes" : "no";

type N = Naked<string | number>; // "yes" | "no"
type W = Wrapped<string | number>; // "no"

type Direct = string | number extends string ? "yes" : "no"; // "no"

Naked asks about string and number separately and gets one answer for each. Wrapped asks whether (string | number)[] fits string[], which it doesn’t. Direct doesn’t distribute either, because distribution only happens when a type parameter is instantiated with a union. A union written in place is just one type.

A similar surprise: boolean is shorthand for true | false, so ToArray<boolean> comes out as false[] | true[].

Turning distribution off

When you want the union treated as a single type, wrap both sides of extends in one-element tuples:

type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;

type B1 = ToArrayWhole<string | number>; // (string | number)[]
type B2 = ToArrayWhole<boolean>; // boolean[]

[T] is a tuple type, not a naked parameter, so no distribution happens. Wrapping the right side as well keeps the meaning of the test the same: [X] extends [Y] holds exactly when X extends Y would for the union as a whole. Wrapping only the left side would change what you’re comparing.

Use the tuple form whenever the question is about the union as a whole. “Is this whole type assignable to string?” is one such question. “Is this type a union at all?” is another.

never in, never out

The trickiest consequence involves never. The compiler treats never as a union with no members. Distribute a conditional over it, and the conditional runs once per member, which is zero times. The union of no results is never:

type IsNeverNaive<T> = T extends never ? true : false;
type IsNever<T> = [T] extends [never] ? true : false;

type I1 = IsNeverNaive<never>; // never
type I2 = IsNever<never>; // true
type I3 = IsNever<string>; // false

IsNeverNaive<never> never even looks at its branches. Neither true nor false comes back. This also means any distributive helper silently returns never when given never, which can hide bugs: a type that should have produced an error or a fallback just disappears. The tuple wrapper fixes IsNever, and it’s the standard way to write that check.

About the video

Dimitri Mitropoulos’s video on the Michigan TypeScript channel covers this one topic in about eight minutes. According to its description and chapters, it explains what distribution over a naked type parameter does and how to turn it off with the [T] extends [U] wrapper, which are the two halves of this lesson. Watch it after the “rule” and “what counts as naked” sections. Andrew Burgess’s video, linked below, shows distribution helping and hurting when working with discriminated unions, and the Prisma meetup talk goes further into the mechanics if you want the long version.

Check yourself

  1. 01Given `type ToArray<T> = T extends unknown ? T[] : never`, what is `ToArray<string | number>`, and why isn't it `(string | number)[]`?

    It is `string[] | number[]`. `T` is a naked type parameter, so the conditional is applied to `string` and to `number` separately, giving `string[]` and `number[]`, and the two results are joined into a union.

  2. 02How does `type Exclude<T, U> = T extends U ? never : T` remove members from a union?

    The conditional distributes over `T`. Each member that is assignable to `U` produces `never`, each other member produces itself, and since `never` disappears from a union, only the members not assignable to `U` remain.

  3. 03How would you change `ToArray` so that `ToArray<string | number>` gives `(string | number)[]`?

    Wrap the checked type and the condition in one-element tuples: `type ToArray<T> = [T] extends [unknown] ? T[] : never`. `[T]` is no longer a naked type parameter, so the union is checked as one type and `T[]` uses the whole union.

  4. 04Why does `type IsNever<T> = T extends never ? true : false` give `never` for `IsNever<never>` rather than `true`?

    `never` behaves as a union with no members. A distributive conditional runs once per member, so with zero members it runs zero times, and the union of zero results is `never`. Writing `[T] extends [never]` avoids distribution and returns `true`.

  5. 05Does `type X = string | number extends string ? 1 : 2` distribute?

    No. Distribution only applies when a type parameter is instantiated with a union. Here the union is written directly, so it is checked as a whole; `string | number` is not assignable to `string`, and the result is `2`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark