Building Configuration Objects Safely
What you'll learn: How to use builder patterns to ensure all required configuration options are set before an object can be used.
Configuration objects are everywhere in software — database connections, API clients, UI components. The problem? When you build them piece by piece, TypeScript can't guarantee you've set all required fields before you finalize them.
The builder pattern with phantom types solves this: you progressively build your config object, and the type system tracks which fields have been set. The build() method only becomes callable once all required fields are present.
The Problem Without Safe Builders
Imagine a configuration object with three required fields:
interface DatabaseConfig {
host: string;
port: number;
database: string;
}
If you allow callers to construct this incrementally, nothing stops them from forgetting a field until runtime.
The Solution: Typed Builder with Conditional Methods
You create a builder class where each setter method returns a new type that tracks what's been set. The build() method uses a conditional type — it only exists when all required fields are present:
type RequiredFields = 'host' | 'port' | 'database';
class ConfigBuilder<TSet extends string = never> {
private config: Partial<DatabaseConfig> = {};
setHost(host: string): ConfigBuilder<TSet | 'host'> {
this.config.host = host;
return this as ConfigBuilder<TSet | 'host'>;
}
setPort(port: number): ConfigBuilder<TSet | 'port'> {
this.config.port = port;
return this as ConfigBuilder<TSet | 'port'>;
}
setDatabase(database: string): ConfigBuilder<TSet | 'database'> {
this.config.database = database;
return this as ConfigBuilder<TSet | 'database'>;
}
build(this: ConfigBuilder<RequiredFields>): DatabaseConfig {
return this.config as DatabaseConfig;
}
}
Now the compiler enforces completeness. You can only call build() when TSet extends all of RequiredFields. Each setter adds to the TSet union, progressively unlocking build().
Key takeaway: Builder patterns with phantom type parameters turn partial construction into a compile-time safety guarantee — you cannot finalize an incomplete configuration.