Course contentsShow
← TypeScript
Lesson 1343 of 1,79631. Type-Driven DesignFree lesson

Connection State Machines

Modeling disconnected, connecting, connected, and disconnecting as a proper state machine type.

Connection State Machines

You'll learn: How to model network connection states (disconnected, connecting, connected, disconnecting) as a type-safe state machine using discriminated unions.


The Connection State Problem

Network connections have distinct states with specific allowed data and transitions. A naive approach might use boolean flags or a simple string:

type ConnectionBad = {
  status: "disconnected" | "connecting" | "connected" | "disconnecting";
  socket?: any;
  error?: string;
  startedAt?: number;
};

The problem: This allows impossible combinations like status: "disconnected" with a socket value, or status: "connected" with an error but no socket.


The State Machine Solution

Model each state as its own distinct type with only the relevant data:

type ConnectionState =
  | { status: "disconnected" }
  | { status: "connecting"; startedAt: number }
  | { status: "connected"; socket: WebSocket; connectedAt: number }
  | { status: "disconnecting"; socket: WebSocket; reason: string };

Each variant carries only the data that makes sense for that state:

  • disconnected: no connection data needed
  • connecting: when we started attempting
  • connected: the active socket and timestamp
  • disconnecting: the socket being closed and why

This makes impossible states impossible—you cannot have a socket without being connected or disconnecting.


Benefits

When you switch on status, TypeScript narrows to the exact state shape:

function handleConnection(state: ConnectionState) {
  switch (state.status) {
    case "disconnected":
      // state has no other properties here
      break;
    case "connecting":
      // state.startedAt is available
      break;
    case "connected":
      // state.socket and state.connectedAt exist
      break;
    case "disconnecting":
      // state.socket and state.reason exist
      break;
  }
}

Key Takeaway: Model state machines as discriminated unions where each state variant contains only the data valid for that state—TypeScript enforces correctness at every transition.