Senior LevelJavaScript & TypeScript
How to design type-safe builder patterns and fluent APIs in TypeScript?
❓ Interview Prompt: Explain chaining method signatures, mandatory parameter tracking using mapped types/generics, and compile-time step verification.
The Builder Pattern constructs complex objects step-by-step. In TypeScript, generic step tracking can enforce at compile-time that all required properties are set before .build() can be invoked!
Pattern Mechanics:
Use an accumulator generic type T inside the builder class. Each setter method returns a new Builder instance typed as Builder<T & { newProp: Type }>. The .build() method is only callable when T satisfies the complete required interface!
Code Implementation Example
typescript
interface RequestConfig {
url: string;
method: 'GET' | 'POST';
headers: Record<string, string>;
}
// Type-safe Builder enforcing mandatory 'url' and 'method'
class RequestBuilder<T extends Partial<RequestConfig> = {}> {
private config: Partial<RequestConfig> = {};
setUrl(url: string): RequestBuilder<T & { url: string }> {
this.config.url = url;
return this as any;
}
setMethod(method: 'GET' | 'POST'): RequestBuilder<T & { method: 'GET' | 'POST' }> {
this.config.method = method;
return this as any;
}
// build() is ONLY callable when url and method are provided!
build(this: RequestBuilder<RequestConfig>): RequestConfig {
return this.config as RequestConfig;
}
}
// ✅ Valid build chain
const req = new RequestBuilder()
.setUrl('/api/data')
.setMethod('GET')
.build();
// ❌ Compile Error if build() is called before setUrl!
// new RequestBuilder().setMethod('GET').build();💡Compile-time mandatory property step verification using generic type accumulation.
🎯 Interview Key Takeaway
Use type-accumulator generics in builder classes to enforce required initialization steps at compile time.
#TypeScript#Builder Pattern#Fluent API#Senior
Back to all JavaScript & TypeScript Questions→