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
- The Builder Pattern Basics
- Fluent Interfaces with Types
- Enforcing Required Steps
- Immutable Builders