0
0
Typescriptprogramming~10 mins

Discriminated union state machines in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Discriminated union state machines
Start: Initial State
Check current state's 'type'
Match 'type' with case
StateA
Perform action
Transition to next state
Repeat or End
The machine starts in an initial state, checks the state's 'type' property, matches it to a case, performs actions, then transitions to the next state, repeating until done.
Execution Sample
Typescript
type State =
  | { type: 'idle' }
  | { type: 'loading' }
  | { type: 'success'; data: string };

function nextState(state: State): State {
  switch(state.type) {
    case 'idle': return { type: 'loading' };
    case 'loading': return { type: 'success', data: 'Done!' };
    case 'success': return { type: 'idle' };
  }
}
This code defines a state machine with three states and a function to move to the next state based on the current state's type.
Execution Table
StepCurrent StateState.typeActionNext State
1{ type: 'idle' }idleMatch 'idle' case, transition to 'loading'{ type: 'loading' }
2{ type: 'loading' }loadingMatch 'loading' case, transition to 'success' with data{ type: 'success', data: 'Done!' }
3{ type: 'success', data: 'Done!' }successMatch 'success' case, transition to 'idle'{ type: 'idle' }
4{ type: 'idle' }idleCycle repeats or stopsDepends on usage
💡 The machine cycles through states by matching the 'type' property and transitioning accordingly.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
state{ type: 'idle' }{ type: 'loading' }{ type: 'success', data: 'Done!' }{ type: 'idle' }Depends on usage
Key Moments - 3 Insights
Why do we use the 'type' property to decide the next state?
The 'type' property uniquely identifies each state variant, allowing the switch-case to safely and clearly select the correct transition, as shown in execution_table steps 1-3.
What happens if we add a new state but forget to handle it in the switch?
TypeScript will warn about missing cases if using exhaustive checks, preventing runtime errors. Without handling, the machine might return undefined or behave unexpectedly, breaking the flow seen in execution_table.
Why does the 'success' state include extra data?
Some states carry additional information needed for actions or transitions. Here, 'success' holds 'data' to represent result info, which is part of the discriminated union pattern.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2. What is the 'state.type' value?
Aloading
Bsuccess
Cidle
Derror
💡 Hint
Check the 'State.type' column in execution_table row for Step 2.
At which step does the state include extra data besides 'type'?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Current State' column and find where 'data' appears.
If we add a new state 'error' but do not add a case for it, what likely happens?
AThe machine crashes immediately.
BThe machine transitions to 'idle' automatically.
CTypeScript will warn about missing case handling.
DThe 'error' state is handled by default.
💡 Hint
Refer to key_moments about missing switch cases and TypeScript checks.
Concept Snapshot
Discriminated union state machines use a 'type' property to identify states.
Use a switch on 'type' to decide transitions.
Each state can have extra data.
TypeScript ensures all states are handled.
This pattern makes state logic clear and safe.
Full Transcript
This example shows a state machine in TypeScript using discriminated unions. The machine has three states: 'idle', 'loading', and 'success'. Each state is an object with a 'type' property. The function nextState takes the current state and uses a switch on state.type to decide the next state. It moves from 'idle' to 'loading', then to 'success' with data, then back to 'idle'. The execution table traces each step, showing the current state, the matched type, the action taken, and the next state. The variable tracker shows how the 'state' variable changes after each step. Key moments explain why the 'type' property is important, what happens if a state is not handled, and why some states carry extra data. The visual quiz tests understanding of state types at steps, presence of extra data, and TypeScript's role in catching missing cases. The snapshot summarizes the pattern as a safe, clear way to manage state transitions using discriminated unions.