Discriminated Union With Exhaustive Switch

Model variants as a union of objects sharing a literal tag and use a never-checked default to guarantee every case is handled.

TypescriptData Integrity

Code

typescriptsnippet
19 lines
export type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number }
  | { kind: "triangle"; base: number; height: number };

export function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
    case "triangle":
      return (shape.base * shape.height) / 2;
    default: {
      const unreachable: never = shape;
      throw new Error("unhandled shape: " + JSON.stringify(unreachable));
    }
  }
}

How it works

Count the function area as the entire surface area of Discriminated Union With Exhaustive Switch.

The failure path is explicit — Error is raised when the guard condition holds.

Using it

The primary signature is export function area(shape: Shape)

The surface worth importing is area; the helpers around it are private to the snippet.

Key statements

throw new Error("unhandled shape: " + JSON.stringify(unreachable));
return (shape.base * shape.height) / 2;
return Math.PI * shape.radius ** 2;

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
`Error` is raised at the guard, so invalid state never reaches the main logic.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `area` at load time.