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?
✗ Incorrect
The discriminant property is a common property with unique literal values that helps TypeScript identify the current type.
In a state machine using discriminated unions, how do you typically check the current state?
✗ Incorrect
A switch on the discriminant property lets TypeScript narrow the type safely for each state.
What benefit does TypeScript provide when handling all states in a discriminated union?
✗ Incorrect
TypeScript can warn about missing cases, helping prevent bugs from unhandled states.
Which of these is a valid discriminated union type for a simple state machine?
✗ Incorrect
Option B uses a common property 'status' with unique literal types, which is a discriminated union.
What TypeScript feature helps catch missing cases in a discriminated union switch?
✗ Incorrect
Using 'never' in a default case forces TypeScript to check exhaustiveness of the switch.
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.