~/alexsh.blog

$ cat advanced-typescript/04-distributive-conditional-types.md

Distributive Conditional Types

February 9, 20261 min readpart 04/20

Difficulty: Intermediate. Prerequisites: Union types, conditional types, generics.

Distributive conditional types automatically distribute over union types when the checked type is a naked type parameter. This behavior allows you to apply transformations to each member of a union independently. Understanding when distribution occurs (and how to prevent it) is crucial for writing predictable type utilities.

Key concepts

  • Automatic distribution over naked type parameters in unions
  • Preventing distribution by wrapping in tuple: [T] extends [U]
  • The difference between distributed and non-distributed results
  • Extract and Exclude as canonical distributive type examples
  • Distribution behavior with never type

Example

codets
// Distributive (naked type parameter)
type ToArray<T> = T extends any ? T[] : never;
type Distributed = ToArray<string | number>; // string[] | number[]

// Non-distributive (wrapped in tuple)
type ToArrayND<T> = [T] extends [any] ? T[] : never;
type NonDist = ToArrayND<string | number>; // (string | number)[]

// Reimplements the built-in Extract/Exclude
type MyExtract<T, U> = T extends U ? T : never;
type MyExclude<T, U> = T extends U ? never : T;

type Strings = MyExtract<string | number | boolean, string>; // string
type NoStr = MyExclude<string | number | boolean, string>;   // number | boolean

// never is the empty union — distributing over it returns never
type N = ToArray<never>; // never

// Check if type is union
type IsUnion<T, U = T> = T extends any ? [U] extends [T] ? false : true : never;
type Test1 = IsUnion<string>;          // false
type Test2 = IsUnion<string | number>; // true

// Real-world: type-fest's IsNever guard (prevents distribution over never)
type IsNever<T> = [T] extends [never] ? true : false;
type A = IsNever<never>;  // true
type B = IsNever<string>; // false

Resources

Practice

Hints

  • Wrap both sides in a tuple [T] extends [U] to prevent distribution over unions.
  • Remember that never is the empty union — distributing over never returns never.