Builder Pattern - Step-by-Step Object Construction in TypeScript

Master the Builder pattern for constructing complex objects step by step. Learn fluent API design, method chaining, and the director pattern in TypeScript.

Creational

Detailed Explanation

Builder Pattern

The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. It is especially useful when an object has many optional parameters.

The Telescoping Constructor Problem

Without Builder, constructors with many parameters become unreadable:

// Hard to read: what does each argument mean?
new QueryBuilder("users", true, false, 100, 0, "name", "asc");

With Builder, each parameter is set via a named method:

new QueryBuilder("users")
  .select(["name", "email"])
  .where("active", true)
  .orderBy("name", "asc")
  .limit(100)
  .build();

Fluent API Design

The key to a great builder is method chaining: each setter returns this, allowing calls to be chained. The final build() method validates the accumulated state and produces the immutable product.

Director (Optional)

A Director class can define preset construction sequences:

class QueryDirector {
  buildActiveUsersQuery(builder: QueryBuilder) {
    return builder
      .select(["name", "email"])
      .where("active", true)
      .orderBy("created_at", "desc")
      .build();
  }
}

Validation

A well-designed builder validates in the build() method, throwing descriptive errors if required fields are missing or if the configuration is internally inconsistent.

Real-World Examples

Builder is ubiquitous in modern libraries: Express.js request/response, Prisma query builders, Knex.js, Zod schema definitions, and HTTP client configurations all use builder-like APIs.

Use Case

Builder is ideal for constructing HTTP requests with many optional headers and parameters, building database queries with dynamic filters and joins, creating configuration objects with dozens of optional settings, and assembling complex UI components with many optional props.

Try It — Design Pattern Reference

Open full tool