0Pricing
TypeScript Academy · Lesson

Fluent Interfaces with Types

Chain methods while tracking accumulated state in types.

Tracking What Was Set

A plain builder lets you call build() at any time, even with required fields missing. We can do better by tracking accumulated state in the type system using a generic type parameter.

A State Type Parameter

We give the builder a generic S that records which keys have been provided so far. As each method runs, we widen S to include a new key.

class Builder<S> {
  // S is a record of keys set so far, e.g. {} or { url: string }
  private data: Record<string, unknown> = {};
}

All lessons in this course

  1. The Builder Pattern Basics
  2. Fluent Interfaces with Types
  3. Enforcing Required Steps
  4. Immutable Builders
← Back to TypeScript Academy