Skip to content

Type-Safe Builder Pattern

Medium ~25 min

What you'll build

A QueryBuilder that uses method chaining to build a query object. Each method returns the builder for chaining, and the build() method returns the final typed query.

Goals

  • Implement the fluent builder pattern
  • Use method chaining with return types
  • Build complex objects step by step
  • Apply generics to a class-based pattern

Prerequisites

  • Classes
  • Generics
  • Method chaining

Steps

  1. 1

    Define the query types

    Create interfaces for the query parts: filter, sort, and pagination. The final query combines them.

    Code
    interface Filter { field: string; op: string; value: unknown; }
    interface Query { table: string; filters: Filter[]; limit?: number; sort?: string; }

    Expected result

    Query and Filter interfaces are defined.

  2. 2

    Write the builder class

    Create a QueryBuilder class with fluent methods. Each method returns this for chaining. The build method returns the final Query.

    Code
    class QueryBuilder {
      private query: Partial<Query> = { filters: [] };
      table(name: string): this { this.query.table = name; return this; }
      where(field: string, op: string, value: unknown): this {
        this.query.filters!.push({ field, op, value }); return this;
      }
      limit(n: number): this { this.query.limit = n; return this; }
      sortBy(field: string): this { this.query.sort = field; return this; }
      build(): Query {
        if (!this.query.table) throw new Error("Table is required");
        return this.query as Query;
      }
    }

    Expected result

    A fluent builder that constructs queries step by step.

  3. 3

    Use the builder

    Chain methods to build a query. The fluent API reads naturally and the result is fully typed.

    Code
    const q = new QueryBuilder()
      .table("users")
      .where("age", ">", 18)
      .where("active", "=", true)
      .sortBy("name")
      .limit(10)
      .build();
    console.log(q); // { table: "users", filters: [...], limit: 10, sort: "name" }

    Expected result

    A fully constructed, typed query object built via fluent chaining.

  4. 4

    Add type guards & runtime checks

    Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.

    Code
    type User = { id: number; name: string };
    
    function isUser(value: unknown): value is User {
      if (typeof value !== "object" || value === null) return false;
      const obj = value as Record<string, unknown>;
      return typeof obj.id === "number" && typeof obj.name === "string";
    }
    
    // Usage with unknown input
    const data: unknown = JSON.parse(rawJson);
    if (isUser(data)) {
      console.log(data.name); // TS knows data is User here
    } else {
      console.error("Invalid user data");
    }

    Expected result

    When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.

  5. 5

    Add generic utility functions

    Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.

    Code
    function groupBy<T, K extends string | number>(
      items: T[],
      keyFn: (item: T) => K
    ): Record<K, T[]> {
      const result = {} as Record<K, T[]>;
      for (const item of items) {
        const key = keyFn(item);
        (result[key] ??= []).push(item);
      }
      return result;
    }
    
    // Usage
    const byAge = groupBy(users, u => u.age);

    Expected result

    groupBy groups any array by key, returning a type-safe Record.

Try it yourself

What you learned

You implemented the builder pattern with TypeScript's this return type for fluent chaining. The builder accumulates partial state and validates completeness in build(). This pattern is used in libraries like Knex (SQL), Mongoose (MongoDB), and Axios (HTTP).

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic