Enforcing Required Properties with Branded Types
What you'll learn: How to use branded types within builders to track which properties have been set at the type level, preventing incomplete objects from being constructed.
The Problem with Optional Builders
Traditional builder patterns let you set properties fluently, but they can't enforce at compile-time that you've actually set all required properties before calling .build(). You might end up with incomplete objects that only fail at runtime.
The Branded Type Solution
By combining branded types with conditional types, you can create a builder that tracks state in the type system. Each time you call a setter method, the builder's type changes to reflect that a specific property has been "marked complete."
Think of it like a checklist where TypeScript won't let you proceed until every box is checked — except the checklist exists entirely at the type level.
How It Works
You create branded types for each required property (like { __usernameBrand: true }), then use intersection types to accumulate these brands as setters are called. The build() method uses a conditional type to check that all required brands are present before allowing construction.
type WithUsername = { __usernameBrand: true };
type WithEmail = { __emailBrand: true };
type HasAll<T, Required> = Required extends T ? true : false;
class UserBuilder<TSet = {}> {
private data: Partial<{ username: string; email: string }> = {};
username(value: string): UserBuilder<TSet & WithUsername> {
this.data.username = value;
return this as never;
}
email(value: string): UserBuilder<TSet & WithEmail> {
this.data.email = value;
return this as never;
}
build(this: UserBuilder<WithUsername & WithEmail>) {
return this.data as { username: string; email: string };
}
}
const user = new UserBuilder()
.username("alice")
.email("alice@example.com")
.build(); // ✓ OK
// new UserBuilder().username("bob").build(); // ✗ Error: email not set
Key Takeaway: By branding the builder's generic type parameter with tokens representing "completion," you enforce that all required setters must be called before .build() succeeds, catching incomplete objects at compile-time rather than runtime.