← TypeScript

Patterns & principles · 6 of 10 · 15 min read

The Builder pattern

Step-by-step construction where the type changes as you go — so build() does not exist until the required pieces have actually been supplied.

  • Design patterns

A builder constructs something in steps instead of in one call. In JavaScript it is a fluent chain that hopes you called the right methods; in TypeScript the builder’s type can track what has been set, so calling build() too early is a compile error.

The ordinary fluent builder

interface Query {
  table: string;
  columns: readonly string[];
  where?: string;
  limit?: number;
}

class QueryBuilder {
  #query: Partial<Query> = { columns: ["*"] };

  from(table: string): this {
    this.#query.table = table;
    return this;
  }

  select(...columns: string[]): this {
    this.#query.columns = columns;
    return this;
  }

  where(clause: string): this {
    this.#query.where = clause;
    return this;
  }

  build(): Query {
    if (!this.#query.table) throw new Error("from() is required");
    return this.#query as Query;
  }
}

const query = new QueryBuilder().select("id", "name").from("users").where("id = 1").build();
console.log(query.table, query.columns);

Note : this rather than : QueryBuilder as the return type. this is a polymorphic type: a subclass’s method returns the subclass, so a chain through an inherited method keeps the extended API available.

class Base { a(): this { return this; } }
class Extended extends Base { b(): this { return this; } }

new Extended().a().b();  // works — `a()` returned Extended
// With `a(): Base`, the chain would stop here.
console.log(typeof new Extended().a);

The remaining problem is the throw in build(): forgetting from() is a runtime error, found by whoever runs the code.

Making the compiler require the steps

interface Query {
  table: string;
  columns: readonly string[];
  where?: string;
}

class Builder<Set extends keyof Query = never> {
  #query: Partial<Query> = {};

  from(table: string): Builder<Set | "table"> {
    this.#query.table = table;
    return this as Builder<Set | "table">;
  }

  select(...columns: string[]): Builder<Set | "columns"> {
    this.#query.columns = columns;
    return this as Builder<Set | "columns">;
  }

  where(clause: string): Builder<Set | "where"> {
    this.#query.where = clause;
    return this as Builder<Set | "where">;
  }

  build(this: Builder<"table" | "columns">): Query {
    return this.#query as Query;
  }
}

const ok = new Builder().from("users").select("id").build();
console.log(ok.table);

// new Builder().from("users").build();
// The 'this' context of type 'Builder<"table">' is not assignable to
// method's 'this' of type 'Builder<"table" | "columns">'.

Two mechanisms are doing the work. The Set parameter accumulates a union of the keys that have been supplied — it starts as never, the empty union, and each setter adds its own. And build declares a this parameter: a fake first parameter, erased at compile time, that constrains what this must be for the method to be callable.

build() is therefore not available on a builder that has not been through from() and select(). The error names the missing state, and autocomplete stops offering build until the chain is complete.

Needed Mechanism
Chaining that survives subclassing return this
Track which steps have run an accumulating type parameter
Forbid a method until then a this parameter on the method
Forbid calling a step twice Exclude the key from the next builder’s methods
Produce an exact result type map the accumulated keys back to the shape

The last row is the version that gives the caller a precise result rather than the whole interface:

interface Fields { id: number; name: string; email: string }

class Picker<Set extends keyof Fields = never> {
  #values: Partial<Fields> = {};

  set<K extends Exclude<keyof Fields, Set>>(key: K, value: Fields[K]): Picker<Set | K> {
    this.#values[key] = value;
    return this as unknown as Picker<Set | K>;
  }

  build(): Pick<Fields, Set> {
    return this.#values as Pick<Fields, Set>;
  }
}

const result = new Picker().set("id", 1).set("name", "Ana").build();
// result: { id: number; name: string } — exactly what was set
console.log(result.id, result.name);
// new Picker().set("id", 1).set("id", 2);  // "id" is excluded the second time

Exclude<keyof Fields, Set> is what makes setting the same key twice an error, and Pick<Fields, Set> is what makes the result type say only what was actually provided.

The cost, honestly

Every setter in these examples contains an assertion, because the compiler cannot verify that mutating #query matches the new type parameter. That is the trade: the public API is precisely typed and the internals are asserted in a handful of one-line places that a reviewer can check.

It is worth it for a builder many people use — a query builder, a test-data builder, a request builder in a published client. It is not worth it for a builder used three times, where an options object is simpler and just as safe:

interface QueryOptions {
  table: string;
  columns: readonly string[];
  where?: string;
  limit?: number;
}

function query(options: QueryOptions): string {
  const where = options.where ? ` where ${options.where}` : "";
  return `select ${options.columns.join(", ")} from ${options.table}${where}`;
}

console.log(query({ table: "users", columns: ["id", "name"], where: "id = 1" }));

Required properties are required, optional ones are optional, the order does not matter, and there are no assertions anywhere. This is the right answer most of the time — reach for a builder when construction is genuinely incremental, when the steps are conditional, or when a fluent chain is the ergonomics you are selling.

A test-data builder

The one place the pattern earns its keep in application code, because test fixtures are exactly “mostly defaults, a few overrides”:

interface User {
  id: number;
  name: string;
  email: string;
  roles: readonly string[];
  active: boolean;
}

function aUser(overrides: Partial<User> = {}): User {
  return {
    id: 1,
    name: "Ana",
    email: "ana@example.com",
    roles: ["user"],
    active: true,
    ...overrides,
  };
}

const admin = aUser({ roles: ["admin"], name: "Root" });
console.log(admin.name, admin.roles, admin.email);

Not a class, not a chain, and it has the builder’s benefit: a test states only what matters to it, and adding a required field to User updates every fixture in one place. The chained form is worth it only when the overrides need validation or derivation.

Common mistakes

: QueryBuilder instead of : this

Mistake. Annotating every chainable method with the class name. Why it fails. A subclass’s inherited method returns the base type, so the chain loses the subclass’s own methods — an error that only appears once someone extends the builder. What to do instead. Return this, which is the polymorphic type.

A build() that throws

Mistake. Validating required steps at runtime with an Error. Why it fails. It is the problem the pattern was supposed to solve, deferred to whoever runs the code — and in TypeScript it is avoidable. What to do instead. An accumulating type parameter plus a this parameter on build, so the method does not exist until the chain is complete.

A builder for four optional fields

Mistake. A fluent class wrapping what is really a configuration object. Why it fails. More code, more assertions, and a worse API — the caller has to discover the method names instead of reading one interface. What to do instead. An options object with ? on the optional members.

Check yourself

One question from the bank on what you just read. Answering here does not affect your quiz history.

How can a Builder refuse to build until the required steps have been called?

Practise Design patterns →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.