Builder Pattern with Fluent Generics
What you'll learn: How to create type-safe builder APIs where each method call progressively refines the generic type being constructed.
What Is the Fluent Generic Builder Pattern?
You've seen how generics make code reusable. Now imagine building an object step-by-step, where each method call teaches TypeScript more about what you're building. Each step returns a new, more specific generic type — like turning a rough sketch into a detailed blueprint as you add features.
This pattern combines:
- Fluent APIs (chaining methods like
builder.with(...).and(...).build()) - Generic refinement (each method narrows the type parameter)
The result? TypeScript knows exactly what properties are required or available at every step.
Core Idea
Instead of a builder that returns this with a fixed type, use a generic type parameter that evolves:
class QueryBuilder<T> {
private fields: string[] = [];
select<K extends keyof T>(field: K): QueryBuilder<T> {
this.fields.push(field as string);
return this;
}
}
// Each call refines what T is
const query = new QueryBuilder<{ id: number; name: string }>()
.select('id') // TypeScript knows 'id' exists
.select('name'); // TypeScript knows 'name' exists
Each .select() call constrains the generic T, ensuring you can only select fields that actually exist.
Practical Example: Building Configuration Objects
class ConfigBuilder<T = {}> {
private config: T;
constructor(initial: T = {} as T) {
this.config = initial;
}
with<K extends string, V>(key: K, value: V): ConfigBuilder<T & Record<K, V>> {
return new ConfigBuilder({ ...this.config, [key]: value } as T & Record<K, V>);
}
build(): T {
return this.config;
}
}
const config = new ConfigBuilder()
.with('port', 3000) // T becomes { port: number }
.with('host', 'localhost') // T becomes { port: number; host: string }
.build(); // Returns { port: number; host: string }
Notice how the type parameter grows with each .with() call using an intersection type.
Key Takeaway: Fluent generic builders use evolving type parameters to create APIs where TypeScript tracks what you've built so far, providing perfect autocompletion and type safety at every step.