0
0
Typescriptprogramming~5 mins

Discriminated union state machines in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a discriminated union in TypeScript?
A discriminated union is a special type of union where each member has a common property with a unique literal type. This property helps TypeScript narrow down the type safely.
Click to reveal answer
beginner
Why use discriminated unions for state machines?
They let you clearly define each state with a unique 'tag' property, making it easy to check the current state and handle transitions safely with TypeScript's type checking.
Click to reveal answer
intermediate
Example of a discriminated union for a traffic light state machine?
type TrafficLight = | { state: 'red'; duration: number } | { state: 'yellow'; duration: number } | { state: 'green'; duration: number }; Each object has a 'state' property that discriminates the union.
Click to reveal answer
intermediate
How does TypeScript help when switching on a discriminated union?
TypeScript narrows the type inside each case block based on the discriminant property, so you get autocompletion and type safety for that specific state.
Click to reveal answer
advanced
What happens if you forget to handle a state in a discriminated union switch?
TypeScript can warn you if you use the 'never' type in a default case, helping you catch missing cases and making your state machine safer.
Click to reveal answer
What property is essential in a discriminated union to distinguish states?
AA numeric index
BA method to change states
CA common property with unique literal values
DAn optional property
In a state machine using discriminated unions, how do you typically check the current state?
AUsing if statements on random properties
BBy using a global variable
CBy checking the object's prototype
DUsing a switch statement on the discriminant property
What benefit does TypeScript provide when handling all states in a discriminated union?
AIt ensures all cases are handled, preventing runtime errors
BIt automatically fixes bugs
CIt runs the code faster
DIt hides unused states
Which of these is a valid discriminated union type for a simple state machine?
Atype State = any
Btype State = { status: 'on' } | { status: 'off' }
Ctype State = { value: number } & { value: string }
Dtype State = number | string
What TypeScript feature helps catch missing cases in a discriminated union switch?
AThe 'never' type in a default case
BThe 'any' type
CThe 'unknown' type
DThe 'void' type
Explain how discriminated unions help build safe state machines in TypeScript.
Think about how TypeScript knows which state you are working with.
You got /4 concepts.
    Describe how you would implement a simple traffic light state machine using discriminated unions.
    Focus on the 'state' property as the discriminator.
    You got /4 concepts.