Course contentsShow
← TypeScript
Lesson 1445 of 1,79633. Inference Inversion PatternsFree lesson

Union Distribution Through infer

How distributive conditional types interact with infer when extracting from union types.

What You'll Learn

You'll learn how TypeScript automatically distributes conditional types over union members when using infer, and how to leverage or prevent this behavior when extracting types from unions.


The Distribution Behavior

When you use infer in a conditional type and pass a union as the input, TypeScript doesn't process the entire union at once. Instead, it distributes the conditional over each union member individually, then combines the results.

Think of it like processing items on a conveyor belt one at a time, rather than handling the entire batch together.


How Distribution Works with infer

type UnwrapArray<T> = T extends (infer U)[] ? U : T;

type Test1 = UnwrapArray<string[] | number[]>;
// Result: string | number

Here's what happens:

  1. TypeScript sees string[] | number[] (a union)
  2. It distributes: processes string[] separately, then number[]
  3. For string[]: infers U = string
  4. For number[]: infers U = number
  5. Combines results: string | number

The Extraction Pattern

This distribution is especially powerful when extracting nested types:

type ExtractPromiseValue<T> = T extends Promise<infer V> ? V : never;

type Values = ExtractPromiseValue<Promise<string> | Promise<number> | boolean>;
// Result: string | number
// (boolean → never, which disappears from the union)

Each union member is checked independently, and non-matching types become never.


Preventing Distribution

Sometimes you want to process the entire union together. Wrap the type parameter in a tuple:

type NoDistribute<T> = [T] extends [(infer U)[]] ? U : T;

type Test2 = NoDistribute<string[] | number[]>;
// Result: string | number (the union itself is treated as the array element type)

The tuple wrapper [T] blocks distribution, forcing TypeScript to treat the union as a single entity.


Practical Use: Filtering Unions

type ExtractFunctions<T> = T extends (...args: any[]) => infer R ? R : never;

type Mixed = (() => string) | number | ((x: number) => boolean) | string;
type Returns = ExtractFunctions<Mixed>;
// Result: string | boolean

Distribution lets you filter the union to only function types, extracting their return types.


Key Takeaway: When infer appears in a distributive conditional type with a union input, TypeScript processes each union member separately and unions the inferred results—giving you precise control over type extraction from complex unions.