BehavioralTypeScriptverifiedVerified

State Pattern in TypeScript

Allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.

How to Implement the State Pattern in TypeScript

1Step 1: Define the state interface and color type

type TrafficLightColor = "red" | "green" | "yellow";

interface TrafficLightState {
  readonly color: TrafficLightColor;
  next(): TrafficLightState;
  canGo(): boolean;
}

2Step 2: Implement concrete state classes

class RedLight implements TrafficLightState {
  readonly color = "red" as const;
  next(): TrafficLightState { return new GreenLight(); }
  canGo(): boolean { return false; }
}

class GreenLight implements TrafficLightState {
  readonly color = "green" as const;
  next(): TrafficLightState { return new YellowLight(); }
  canGo(): boolean { return true; }
}

class YellowLight implements TrafficLightState {
  readonly color = "yellow" as const;
  next(): TrafficLightState { return new RedLight(); }
  canGo(): boolean { return false; }
}

3Step 3: Create the context that delegates to states

class TrafficLight {
  private state: TrafficLightState = new RedLight();

  advance(): void {
    this.state = this.state.next();
  }

  getColor(): TrafficLightColor {
    return this.state.color;
  }

  canGo(): boolean {
    return this.state.canGo();
  }
}

4Step 4: Cycle through states and observe transitions

const light = new TrafficLight();
console.log(light.getColor(), light.canGo()); // red false
light.advance();
console.log(light.getColor(), light.canGo()); // green true
light.advance();
console.log(light.getColor(), light.canGo()); // yellow false
light.advance();
console.log(light.getColor(), light.canGo()); // red false

State Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

State Pattern in the Real World

Think of a traffic light. The light itself (context) doesn't change its wiring, but its active state—red, yellow, or green—completely determines what drivers should do. Each color has its own rules, and the light transitions through states on a timer. Adding a flashing-yellow state only requires defining that state's rules, not rewiring the entire light.