0
0
Typescriptprogramming~3 mins

Why Discriminated union state machines in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could never get confused about what state it's in?

The Scenario

Imagine you are building a program that handles different states, like a traffic light or a login process, and you try to manage each state with separate variables and lots of if-else checks scattered everywhere.

The Problem

This manual way quickly becomes confusing and error-prone. You might forget to check a state, mix up conditions, or write repetitive code that is hard to read and maintain.

The Solution

Discriminated union state machines let you define all possible states clearly in one place with unique tags. This makes your code safer, easier to understand, and TypeScript helps catch mistakes before running your program.

Before vs After
Before
if (state === 'loading') { /* do loading */ } else if (state === 'error') { /* handle error */ } else if (state === 'success') { /* show data */ }
After
type State = { type: 'loading' } | { type: 'error'; message: string } | { type: 'success'; data: string };
switch(state.type) {
  case 'loading': /* do loading */; break;
  case 'error': /* handle error */; break;
  case 'success': /* show data */; break;
}
What It Enables

You can build clear, reliable programs that handle complex states without confusion or bugs.

Real Life Example

Think of a music player app that can be stopped, playing, or paused. Using discriminated unions, you can easily manage what happens in each state and avoid mistakes like trying to pause when already stopped.

Key Takeaways

Manual state checks get messy and error-prone.

Discriminated unions group states with unique tags for clarity.

TypeScript helps catch errors and makes code easier to maintain.