Zest.

TypeScript: Union types and narrowing

A short, tested TypeScript example for union types and narrowing. Copy it and adjust the names and paths for your project.

TypeScript
type Shape =
  | { kind: "circle"; r: number }
  | { kind: "square"; size: number };

function area(s: Shape) {
  switch (s.kind) {
    case "circle": return Math.PI * s.r ** 2;
    case "square": return s.size ** 2;
  }
}

Find it in Zest

Search for “typescript union types and narrowing” in Zest and this example appears above the results, with other matches to choose from. Searches stay private.

More TypeScript examples

All TypeScript examples