Skip to contentSaltar al contenido
125+ QA and SEO checks per page

State Pattern Implementation in TypeScript

14 min readintermediate
Website QA and SEO audits

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

The State pattern lets an object change its behaviour when its internal state changes, by delegating to a per-state object rather than branching on a flag. Written out as classes it is unremarkable; what makes it worth eight separate pages is that this is the pattern where type systems differ most sharply. The real question is not how to represent a state but whether the compiler will tell you when you forget to handle one, and whether it can stop an illegal transition from being written at all. Three languages here prove exhaustiveness at compile time and turn a forgotten state into a build failure. One goes further and can make an invalid transition fail to compile by encoding the state in the type itself. One has an enum construct built specifically for this pattern. And two cannot check any of it, so the discipline has to live in tests.

State Pattern in TypeScript: what you actually reach for

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.

TypeScript implementation

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. Keep the never check in every switch over the union. Derive the transition function signature from the machine definition so the table and the code cannot drift.
typescript
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 Free

The TypeScript-specific 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. 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.

Performance in TypeScript, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port State Pattern between languages.

Real-World Applications

State Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding State Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

State Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose State Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of State Pattern to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.