Extensible Builders with Generics
What you'll learn: How to design builder APIs that can be extended by others while preserving type safety throughout the entire chain of method calls.
The Extension Problem
You've built builders that enforce required properties and maintain type state through method chaining. But what if someone wants to extend your builder with additional methods? Traditional builders break down because each new method needs to return the correct builder type — including any state from parent classes.
The challenge: a subclass method that returns this will narrow the type to the subclass, losing the ability to call parent methods afterward. Generic builders solve this.
The Generic Builder Pattern
The key insight is making the builder generic over itself. Each builder method returns not just this, but a generic type parameter that represents "whatever builder type I'm actually called on":
class BaseBuilder<Self> {
private data: Record<string, unknown> = {};
withProperty<K extends string, V>(
key: K,
value: V
): Self & { [P in K]: V } {
this.data[key] = value;
return this as any;
}
}
This pattern allows extensions to layer additional state without breaking the chain.
Extending with Type Accumulation
When extending the builder, pass the extending class as the generic parameter:
class ExtendedBuilder<Self = ExtendedBuilder<any>>
extends BaseBuilder<Self> {
withValidation(fn: () => boolean): Self {
// Add validation logic
return this as unknown as Self;
}
}
Now calls can be chained in any order, with full autocomplete for all methods from both base and extended builders.
Key Takeaway: Generic builders that are parameterized over their own type enable safe extension by allowing type state to accumulate across inheritance hierarchies, maintaining complete type safety in fluent APIs.