Course contentsShow
← TypeScript
Lesson 659 of 1,79615. Generic ConstraintsFree lesson

Builder Pattern with Progressive Constraints

Implement fluent builders where each method call progressively constrains the type parameter's shape.

Builder Pattern with Progressive Constraints

What you'll learn: How to create type-safe builder APIs where each method call adds new constraints to the type, guiding users to construct valid objects step-by-step.

What Is This Pattern?

Imagine building a house where each construction phase unlocks the next step — you can't add the roof until the walls are up. Progressive constraints in builder patterns work the same way: each builder method returns a new, more constrained type that only allows valid next steps.

This uses TypeScript generics where each method call adds properties to a type parameter, progressively narrowing what's missing and what's available.

The Core Pattern

You create a builder class with a generic type parameter representing the "state" of construction. Each method:

  1. Adds a property to that state type
  2. Returns a new builder with the updated constraint
  3. Only allows build() when all required properties exist
type Builder<T> = {
  withName: <N extends string>(name: N) => Builder<T & { name: N }>;
  withAge: <A extends number>(age: A) => Builder<T & { age: A }>;
  build: T extends { name: string; age: number } ? () => T : never;
};

function createBuilder<T = {}>(): Builder<T> {
  const data: any = {};
  return {
    withName: (name) => { data.name = name; return createBuilder<T & { name: typeof name }>() as any; },
    withAge: (age) => { data.age = age; return createBuilder<T & { age: typeof age }>() as any; },
    build: (() => data) as any
  };
}

// Usage shows progressive constraint building
const person = createBuilder()
  .withName("Alice")  // Now T = { name: "Alice" }
  .withAge(30)        // Now T = { name: "Alice"; age: 30 }
  .build();           // ✓ Allowed: all constraints met

Each method call intersects new properties with T, and build() uses a conditional constraint to only exist when complete.

Key Takeaway: Progressive constraints guide API users through valid construction paths by evolving the type parameter with each builder step, making invalid states unrepresentable.