typestar

Discriminated unions in TypeScript

A shared literal field that makes a union exhaustive.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number }
  | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
    case "square":
      return shape.side ** 2;
  }
}

How it works

  1. Every member carries a distinct kind.
  2. switch on kind narrows to that member.
  3. Covering all cases satisfies the return type.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
338
Tokens
93
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 1 of 3 in Exhaustiveness & tests, step 9 of 12 in Type-level programming.

← Previous Next →