Generic Builder Pattern
What You'll Learn
You'll learn how to use generics to create builder APIs where each method call refines the type to track what's been configured, catching incomplete objects at compile time instead of runtime.
The Core Idea
A builder pattern lets you construct complex objects step-by-step using a fluent chain of method calls. By adding generics, you can make TypeScript track which properties have been set as you go, preventing you from calling .build() until all required fields are present.
Think of it like a multi-step form where each page you complete unlocks the next step. TypeScript ensures you fill out every required page before submitting.
How It Works
Your builder class takes a type parameter representing the current state of construction. Each method returns a new, more specific type that includes the property just set:
type Config<T> = T;
class Builder<T = {}> {
private data: Partial<T> = {};
name(value: string): Builder<T & { name: string }> {
return Object.assign(new Builder<T & { name: string }>(), {
data: { ...this.data, name: value }
});
}
age(value: number): Builder<T & { age: number }> {
return Object.assign(new Builder<T & { age: number }>(), {
data: { ...this.data, age: value }
});
}
build(this: Builder<{ name: string; age: number }>): { name: string; age: number } {
return this.data as { name: string; age: number };
}
}
const person = new Builder()
.name("Alice")
.age(30)
.build(); // ✓ All required fields set
// new Builder().build(); // ✗ Error: missing name and age
Each method call intersects the current type with the new property, gradually building up the complete shape.
Key Takeaway:
The Generic Builder Pattern uses type parameter refinement (Builder<T & { newProp: Type }>) to enforce that all required properties are set before allowing construction, turning runtime validation into compile-time safety.