Course contentsShow
← TypeScript
Lesson 1666 of 1,79638. Common Patterns and AntipatternsFree lesson

Generic Constraints vs Union Bounds

Constraining a generic with a union gives you both type preservation and bounded flexibility.

Generic Constraints vs Union Bounds

You'll learn: How constraining a generic with a union type gives you both type preservation and bounded flexibility—combining the best of generics and unions.


The Problem They Both Solve

You've learned that generics preserve types through operations, while unions combine fixed alternatives. But what if you want both? You need type preservation (like generics) but only within a specific set of allowed types (like unions).

This is where generic constraints with union bounds shine.

How It Works

When you write:

function process<T extends 'create' | 'update' | 'delete'>(action: T): T {
  return action;
}

You're saying: "T can be any of these three literal types, but preserve which one it is."

This is different from:

// Union alone: loses specificity
function process(action: 'create' | 'update' | 'delete'): 'create' | 'update' | 'delete' {
  return action;
}

// Unconstrained generic: too flexible
function process<T>(action: T): T {
  return action;
}

The constrained generic gives you:

  • Bounded flexibility: Only specific types allowed (union behavior)
  • Type preservation: The exact input type flows through (generic behavior)

Real-World Pattern

type Status = 'pending' | 'approved' | 'rejected';

function transition<S extends Status>(from: S, to: S): S {
  // TypeScript knows both 'from' and 'to' are the same specific Status literal
  return to;
}

const result = transition('pending', 'approved');
// result is typed as 'approved', not Status

Think of it like a security checkpoint: generics are like "anyone can pass through," unions are like "only these three people exist," but constrained generics are "preserve each person's identity, but only let these three through."


Key Takeaway: Constraining a generic with a union (<T extends UnionType>) combines type preservation with bounded options—you get autocomplete on allowed values AND maintain the specific type that was passed in, giving you the safety of unions with the precision of generics.