State Machines in Builder Types
You'll learn: How to use TypeScript's type system to model a builder's construction process as a state machine, preventing invalid method calls at compile time.
What This Means
A state machine in builder types means that each builder method returns a new type representing the next valid state. The type system tracks what you've done so far and only allows methods that make sense for the current state.
Think of it like a video game quest progression: you can't fight the final boss until you've collected the magic sword, and you can't collect the magic sword until you've entered the dungeon. Each step unlocks specific next steps.
In builders, this prevents mistakes like calling .build() before setting required properties, or setting the same property twice when that doesn't make sense.
The Core Pattern
Instead of every method returning the same this type, each method returns a different branded type representing a new state:
type Builder<State extends string> = {
_state: State;
};
type WithTitle = Builder<'hasTitle'>;
type WithContent = Builder<'hasContent'> & WithTitle;
type Complete = Builder<'complete'> & WithContent;
declare function createPost(): Builder<'empty'>;
declare function title(builder: Builder<'empty'>): WithTitle;
declare function content(builder: WithTitle): WithContent;
declare function build(builder: WithContent): Complete;
// Valid progression:
const post = build(content(title(createPost())));
// Invalid: can't build without content
// const invalid = build(title(createPost())); // Error!
Each function accepts a specific state and returns the next state, creating a compile-time state machine that guides valid usage.
Key Takeaway: State machine builders use progressive type refinement—where each method call advances to a new type state—to enforce valid construction sequences at compile time, making invalid builder usage literally un-callable.