discriminated union

When every type in a union contains a common property with literal types, TypeScript considers that to be a discriminated union, and can narrow out the members of the union.

interface Circle {
  kind: "circle";      // common property with literal types
  radius: number;
}
 
interface Square {
  kind: "square";      // common property with literal types
  sideLength: number;
}

// ⭐️ `kind` is considered a discriminant property of `Shape`
type Shape = Circle | Square;

// switch on shape.kind
function getArea(shape: Shape) {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2; 
    case "square": return shape.sideLength ** 2;
  }
}

Last updated