Discriminated Union State Machines
📖 Scenario: You are building a simple traffic light controller that changes states based on events. Each state has a unique name and specific data. Using discriminated unions helps manage these states clearly and safely.
🎯 Goal: Create a TypeScript program that defines a discriminated union type for traffic light states, writes a function to transition between states, and prints the current state.
📋 What You'll Learn
Define a discriminated union type called
TrafficLightState with three states: red, yellow, and green.Each state should have a
type property with a string literal matching the state name.Add a
duration property (number) to each state representing how long the light stays in that state.Create a variable called
currentState of type TrafficLightState and initialize it to the red state with duration 30.Write a function called
nextState that takes a TrafficLightState and returns the next state in the cycle: red -> green -> yellow -> red.Use a
switch statement on the type property inside nextState to determine the next state.Print the
type and duration of the currentState after transitioning through all states once.💡 Why This Matters
🌍 Real World
State machines are used in user interfaces, games, and hardware controllers to manage different modes or statuses clearly and safely.
💼 Career
Understanding discriminated unions and state machines is valuable for frontend and backend developers to write robust and maintainable code that handles complex state logic.
Progress0 / 4 steps