TypeScript · Narrowing and unions

Discriminated union

A shared literal field lets TypeScript narrow the whole object in a switch.

Syntax
type Shape = { kind: "circle"; r: number } | …

Example

Example
type Shape =
  | { kind: "circle"; r: number }
  | { kind: "square"; size: number };
function area(shape: Shape) {
  return shape.kind === "circle" ? Math.PI * shape.r ** 2 : shape.size ** 2;
}

More in this group

Assertion function Exhaustive switch in operator instanceof guard Non-null assertion Type assertion Type predicate typeof guard

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course