Typed Dispatch Table Handles Every Event Kind

A mapped handler object keyed by the event discriminant makes dispatch exhaustive: adding a kind without a handler breaks the object literal at compile time.

TypescriptData Integrity

Code

typescriptsnippet
30 lines
type Event =
  | { kind: "deploy"; env: string }
  | { kind: "alert"; code: number }
  | { kind: "ping" };

const handlers: { [K in Event["kind"]]: (event: Extract<Event, { kind: K }>) => string } = {
  deploy: (e) => `deploying to ${e.env}`,
  alert: (e) => `alert ${e.code}`,
  ping: () => "pong",
};

// dispatch is exhaustive: adding a kind without a handler breaks the object literal
function dispatch(event: Event): string {
  return handlers[event.kind](event);
}

const events: Event[] = [
  { kind: "deploy", env: "staging" },
  { kind: "alert", code: 503 },
  { kind: "ping" },
];

for (const event of events) {
  console.log(dispatch(event));
}

// Extract pulls the single variant back out of the union for one handler
type AlertEvent = Extract<Event, { kind: "alert" }>;
const alertOnly: AlertEvent = { kind: "alert", code: 429 };
console.log(handlers.alert(alertOnly));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

deploying to staging
alert 503
pong
alert 429

How it works

Typed Dispatch Table Handles Every Event Kind is built around the function dispatch.

The file repeats itself only inside for (const event of events).

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

Signature: function dispatch(event: Event)

Key statements

const handlers: { [K in Event["kind"]]: (event: Extract<Event, { kind: K }>) => string } = {
deploy: (e) => `deploying to ${e.env}`,
alert: (e) => `alert ${e.code}`,
ping: () => "pong",
};
return handlers[event.kind](event);

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `dispatch` at load time.