RecipesChapter 3: The Type System

Explicitly Defining Models with Discriminated Union Types

Recipe 3.2 from The TypeScript Cookbook

function area(shape: Shape) {
  switch (shape.kind) {
    case "circle": // shape is Circle
      return Math.PI * shape.radius * shape.radius;
    case "triangle": // shape is Triangle
      return (shape.x * shape.y) / 2;
    case "square": // shape is Square
      return shape.x * shape.x;
    default:
      throw Error("not possible");
  }
}
Open in TypeScript Playground →