Dev Helpers
← Back

Build a correlated event union

Build a correlated event union using TypeScript.

Open this example in the interactive library

Source code

type Events = {
  start: { id: number };
  finish: { ms: number };
  failure: { reason: string };
};
console.log(
  (() => {
    type Event = {
      [K in keyof Events]: { type: K; data: Events[K] };
    }[keyof Events];
    const event: Event = { type: "failure", data: { reason: "timeout" } };
    return event.data.reason;
  })(),
);

Sample output

timeout