Course contentsShow
← TypeScript
Lesson 1073 of 1,79625. The this TypeFree lesson

Real-World Builder Pattern Example

Implementing a type-safe builder with polymorphic this for extensible configuration.

Real-World Builder Pattern Example

What you'll learn: How to implement a type-safe, fluent API builder using polymorphic this to create extensible configuration objects with compile-time guarantees.

The Real-World Scenario

Imagine you're building a query builder for a database ORM, or an HTTP client configurator, or a form validator. These all share a pattern: you want users to chain method calls fluently (query.select().where().limit()), and each method should return the builder itself for further chaining. Without polymorphic this, inheritance breaks this pattern.

The Implementation Pattern

With polymorphic this, you create a base builder class where methods return this (the type, not the value). When subclasses extend it, those methods automatically return the subclass type, not the base type:

class QueryBuilder {
  private selectClause: string[] = [];
  private whereClause: string[] = [];

  select(...fields: string[]): this {
    this.selectClause.push(...fields);
    return this;
  }

  where(condition: string): this {
    this.whereClause.push(condition);
    return this;
  }

  build(): string {
    return `SELECT ${this.selectClause.join(', ')} WHERE ${this.whereClause.join(' AND ')}`;
  }
}

class PaginatedQueryBuilder extends QueryBuilder {
  private limitValue?: number;
  private offsetValue?: number;

  limit(n: number): this {
    this.limitValue = n;
    return this;
  }

  offset(n: number): this {
    this.offsetValue = n;
    return this;
  }
}

// Fully type-safe chaining!
const query = new PaginatedQueryBuilder()
  .select('id', 'name')
  .where('active = true')
  .limit(10)      // ✓ Available because we instantiated PaginatedQueryBuilder
  .offset(20);    // ✓ Still returns the correct subclass type

Without this, the base class methods would return QueryBuilder, losing access to limit() and offset() after calling select() or where().

Why This Matters

This pattern powers real libraries like TypeORM, Prisma's query builders, and testing frameworks. It provides extensibility — new subclasses add methods without rewriting the base — while maintaining perfect autocomplete and type safety throughout the chain.

Key Takeaway: Polymorphic this enables type-safe builder patterns where each method returns the actual instance type, making method chaining work correctly even through inheritance and allowing builders to be extended without breaking the fluent API.