State Pattern Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓State Pattern runs in O(1) time and O(n) space, in TypeScript as in every other language.
- ✓A discriminated union of state objects plus a switch is the idiomatic machine, and it is the version that gets a real compile-time guarantee: assigning the narrowed value to a never-typed variable in the default branch makes the compiler reject the code the moment a state is added and not handled.
- ✓Model each state as its own object type carrying exactly the data valid in that state, rather than one type with optional fields, because that is what makes impossible states unrepresentable: a draft has no publishedAt and the compiler knows it.
- ✓The TypeScript trap: The exhaustiveness proof rests entirely on the never assignment; a default branch that throws compiles fine and quietly stops checking, so the guarantee people believe they have often is not there.
- ✓Everything erases, so the emitted code is the switch. The compile-time cost is where the trade sits: a template-literal type encoding every legal transition grows combinatorially with the number of states and events, and a machine with a few dozen of each can make tsc noticeably slow and hit the instantiation depth limit.
What State Pattern actually is
State Pattern in TypeScript: what you actually reach for
TypeScript implementation
type State =
| { readonly tag: 'draft'; readonly body: string }
| { readonly tag: 'review'; readonly body: string; readonly reviewer: string }
| { readonly tag: 'published'; readonly body: string; readonly publishedAt: Date };
// Impossible states are unrepresentable: a draft simply HAS no publishedAt.
function label(s: State): string {
switch (s.tag) {
case 'draft': return 'Draft';
case 'review': return 'With ' + s.reviewer;
case 'published': return 'Live since ' + s.publishedAt.toISOString();
default: {
const _exhaustive: never = s; // adding a state breaks the BUILD here
return _exhaustive;
}
}
}
// Type-level transition table: an illegal event is a compile error.
type Transitions = {
draft: 'submit';
review: 'approve' | 'reject';
published: never;
};
declare function send<S extends State['tag']>(from: S, event: Transitions[S]): State;
send('draft', 'submit');
// send('draft', 'approve'); // compile error: not assignable to 'submit'Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for State Pattern?
A discriminated union of state objects plus a switch is the idiomatic machine, and it is the version that gets a real compile-time guarantee: assigning the narrowed value to a never-typed variable in the default branch makes the compiler reject the code the moment a state is added and not handled. Template literal types can express the transition table at the type level, so an illegal event for a given state is a compile error at the call site. Const type parameters, from TypeScript 5.0, keep a literal machine definition narrow without an as const at every use.
What is the most common TypeScript mistake when implementing State Pattern?
The exhaustiveness proof rests entirely on the never assignment; a default branch that throws compiles fine and quietly stops checking, so the guarantee people believe they have often is not there. The second trap is that narrowing is lost across an await or a callback boundary: the compiler narrows a union inside an if, but if you await in that block the value may have changed at run time while the narrowed type persists, so an async transition can operate on a state it has already left with the compiler still insisting it is fine.
How does State Pattern actually perform in TypeScript?
Everything erases, so the emitted code is the switch. The compile-time cost is where the trade sits: a template-literal type encoding every legal transition grows combinatorially with the number of states and events, and a machine with a few dozen of each can make tsc noticeably slow and hit the instantiation depth limit. Keeping the type-level table to the states that genuinely need protection is the practical middle ground. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.