Web Development
TypeScript
Subjective
Oct 04, 2025
How do you implement a type-safe builder pattern?
Detailed Explanation
Type-safe builder pattern uses method chaining with conditional types to track which properties have been set.
Basic Builder Pattern:
interface User {
id: string;
name: string;
email: string;
age?: number;
}
type RequiredKeys = {
[K in keyof T]-?: {} extends Pick ? never : K;
}[keyof T];
type Builder = {
[P in RequiredKeys]: P extends K
? Builder
: (value: T[P]) => Builder;
} & (RequiredKeys extends K ? { build(): T } : {});
class UserBuilder implements Builder {
private user: Partial = {};
id(value: string) {
this.user.id = value;
return this;
}
name(value: string) {
this.user.name = value;
return this;
}
email(value: string) {
this.user.email = value;
return this;
}
build(): User {
return this.user as User;
}
}
// Usage
const user = new UserBuilder()
.id('123')
.name('John')
.email('john@example.com')
.build();
Advanced Generic Builder:
class GenericBuilder {
private data: Partial = {};
set(key: K, value: T[K]) {
this.data[key] = value;
return this;
}
build(): T {
return this.data as T;
}
}
Benefits:
• Ensures required properties are set before building
• Provides excellent IDE autocomplete
• Prevents runtime errors from missing properties
• Creates fluent, readable APIs.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts