Skip to article content
FrontendXLesson 31 / 40

Typing the builder pattern

Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.

advanced · about 45 minutes · 3 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Build an object step by step with a chainable API.
  • Track required fields in the type so build is only callable when complete.
  • Avoid over-engineering the type.

Overview

#

A basic builder

snippet.ts
class QueryBuilder {
  private table = "";
  private limitValue: number | undefined;
  from(table: string): this { this.table = table; return this; }
  limit(n: number): this { this.limitValue = n; return this; }
  build(): string {
    return `SELECT * FROM ${this.table}` + (this.limitValue ? ` LIMIT ${this.limitValue}` : "");
  }
}

Returning this keeps the chain typed.

Tracking required steps

A phantom type parameter records which fields are set.

snippet.ts
interface Builder<Set extends string> {
  from(table: string): Builder<Set | "table">;
  build(this: Builder<"table">): string;
}

build declares a this type that requires table to be present, so calling it early fails to compile.

Trade-off

Fully type-safe builders are powerful but hard to read and slow to check. Use them for public APIs where the guarantee matters; use a plain options object elsewhere.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement a chainable `Builder` with `set(key, value)` returning `this` and `build()` returning the collected record.

    starter.typescript
    export class Builder {
      private data: Record<string, unknown> = {};
      set(key: string, value: unknown): this {
        // your code
      }
      build(): Record<string, unknown> {
        // your code
      }
    }
    

    Reveal the reference answer
    reference.typescript
    export class Builder {
      private data: Record<string, unknown> = {};
      set(key: string, value: unknown): this {
        this.data[key] = value;
        return this;
      }
      build(): Record<string, unknown> {
        return { ...this.data };
      }
    }
    

    Authored expected output: Compiles with no errors. Runtime: new Builder().set("a", 1).build() is { a: 1 }.

    Returning this keeps the fluent chain typed at each step.

  2. Exercise 2Predict

    What does `build()` return? ```ts class B { private parts: string[] = []; add(p: string): this { this.parts.push(p); return this; } build(): string { return this.parts.join("-"); } } ```

    Choose the best answer
  3. Exercise 3Explain

    How can a type parameter track which required fields a builder has set, and why is that useful?

    Reveal the reference answer
    reference.typescript
    The builder carries a phantom type parameter that is a union of the field names already set. Each setter returns a builder with an added member in that union. The terminal build method declares a this type that requires the union to include every mandatory field, so calling build before setting them is a compile error. It turns a runtime completeness check into a compile-time guarantee.

    Authored expected output: A written answer naming a phantom type parameter and compile-time completeness.

    The type parameter is the compile-time record of progress.

Common misconceptions

#
  • Returning this loses type information.
  • A builder must use a class.
  • Phantom type tracking has runtime cost.

Follow-up practice

#
  • typescript-react-props

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.