TypeScript Tutorial

Builder Pattern

Type-safe object construction with fluent interfaces

What is the Builder Pattern?

The Builder Pattern is a design pattern used to construct complex objects step-by-step. In TypeScript, we can use the type system to ensure that an object is only built when all required steps have been completed.

A Basic Fluent Builder

A common implementation uses a class where each method returns this, allowing you to "chain" calls together.
typescript
class RequestBuilder {
    private url: string = "";
    private method: string = "GET";

    setURL(url: string) {
        this.url = url;
        return this; // Return 'this' for chaining!
    }

    setMethod(method: "GET" | "POST") {
        this.method = method;
        return this;
    }

    build() {
        return { url: this.url, method: this.method };
    }
}

const req = new RequestBuilder().setURL("/api").setMethod("POST").build();

Advanced Type-Safe Builder

Wait! We can go further. We can use TypeScript to prevent the user from calling .build() until they have called .setURL().
typescript
type Request = { url: string; method: string };

class Builder<T extends Partial<Request>> {
    constructor(private data: T = {} as T) {}

    setURL(url: string): Builder<T & { url: string }> {
        return new Builder({ ...this.data, url });
    }

    // ... other methods ...

    build(this: Builder<Request>): Request {
        return this.data as Request;
    }
}

Why use the Builder Pattern?

  1. Readability: Makes object construction with many parameters easy to follow.
  2. Immutability: You can create an immutable builder where every step returns a new instance.
  3. Safety: Enforce required fields at compile-time using advanced generics.

Summary

TermDescription
FluentMethods that return this for easy chaining
Step-by-StepBreaking complex construction into small parts
this: TRestricting methods to specific builder states
GenericTracking the "State" of the builder in the type
Best ForAPI Requests, Query Builders, Complex Configs
LogicSeparating the "Construction" from the "Representation"
SafetyCatch missing required fields during development
CleanAvoids the "Telescoping Constructor" anti-pattern
ModernPowering high-level APIs like Prisma and Knex
RecursiveBuilders can return other builders for nested data
ConstraintSlightly more verbose to implement than simple objects
IdentityThe builder is a "Service" that produces a "Value"