#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 29 of 48medium

What are Discriminated Unions?

Type-safe union with common property.

What You'll Learn

  • What discriminated unions are
  • Pattern matching
  • Exhaustive checking

What is a Discriminated Union?

A union type where each member has a common property (discriminant) with a literal type.

code.tsTypeScript
type Circle = {
  kind: "circle";
  radius: number;
};

type Square = {
  kind: "square";
  side: number;
};

type Triangle = {
  kind: "triangle";
  base: number;
  height: number;
};

type Shape = Circle | Square | Triangle;

Pattern Matching

code.tsTypeScript
function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    case "triangle":
      return (shape.base * shape.height) / 2;
  }
}

Exhaustive Checking

code.tsTypeScript
function assertNever(x: never): never {
  throw new Error("Unexpected: " + x);
}

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    case "triangle":
      return (shape.base * shape.height) / 2;
    default:
      return assertNever(shape);
  }
}