Menu

Conditional Types and infer

Lesson 4: Conditional Types and infer

What is a conditional type?

A conditional type chooses between two types based on a check, like a ternary operator for types:

T extends U ? X : Y
Feature Example Result
Basic check IsString<'UPI'> true
Distribution over unions `ToArray<string number>`
Extract with infer ElementType<Product[]> Product
Prevent distribution [T] extends [U] ? X : Y Checks the union as a whole

Example

type IsString<T> = T extends string ? true : false;
type A = IsString<'UPI'>; // true
type B = IsString<42>;    // false

// Distributive: applied to each union member
type ToArray<T> = T extends unknown ? T[] : never;
type C = ToArray<string | number>; // string[] | number[]

// infer: pull a type out of another type
type ElementType<T> = T extends readonly (infer E)[] ? E : never;
type D = ElementType<{ name: string }[]>; // { name: string }

type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;
type E = UnwrapPromise<Promise<number>>; // number

// Practical: the payload type for an event name
type QuickCartEvent =
  | { type: 'cart:add'; productId: string; quantity: number }
  | { type: 'order:placed'; orderId: string; total: number };

type EventPayload<T extends QuickCartEvent['type']> = Extract<QuickCartEvent, { type: T }>;
type Placed = EventPayload<'order:placed'>; // { type: 'order:placed'; orderId: string; total: number }

How it works

  • When T is a bare type parameter and receives a union, the condition runs on each member separately (distributive conditional types). Exclude and Extract rely on this.
  • infer E declares a type variable that TypeScript fills in while matching the pattern.
  • Built-ins such as ReturnType, Parameters, and Awaited are conditional types using infer.

Common mistakes

Mistake Effect Fix
Unexpected results with unions Distribution splits the union Wrap in a tuple: [T] extends [U]
Deeply nested conditional types in app code Slow type-checking, unreadable errors Keep complex types in shared utility files, with tests
Using infer outside a conditional extends clause Syntax error infer only works inside extends ... ?

Key takeaways

  • Conditional types choose types based on a check; infer extracts parts of types.
  • Most built-in utilities are conditional types you can now read and write.

Try it: Write FirstParameter<F> that returns the type of a function's first parameter, using infer.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details