Course contentsShow
← TypeScript
Lesson 582 of 1,79614. Generics in PracticeFree lesson

Builder and Fluent API Patterns

Using generics to track accumulated state in chained method calls.

Builder and Fluent API Patterns

What you'll learn: How to use generics to track state changes through chained method calls, making invalid sequences impossible.

The Challenge with Chained APIs

Builder patterns let you construct objects step-by-step with method chaining:

builder.setName("Alice").setAge(30).build();

But how do you prevent mistakes like calling build() before required properties are set? Generics can track what's been configured!

Tracking State with Type Parameters

Each method returns a new generic type that remembers what's been set:

class QueryBuilder<T = {}> {
  private data: T = {} as T;

  select<K extends string>(field: K): QueryBuilder<T & { [P in K]: string }> {
    return this as any;
  }

  build(): T {
    return this.data;
  }
}

const result = new QueryBuilder()
  .select("name")
  .select("email")
  .build(); // Type is { name: string; email: string }

The type parameter T starts as an empty object {}, and each select() call merges a new property into it. By the time you call build(), T contains the complete shape!

Why This Matters

This technique ensures compile-time correctness in fluent APIs. The type system prevents you from accessing properties you haven't configured, and enforces required steps before calling terminal methods like build().

Key Takeaway: Generics can accumulate type information across chained calls, turning runtime errors into compile-time guarantees and making fluent APIs self-documenting.