Typescript Foundations / Advanced Types

Discriminated Unions

🔸 Discriminated Unions

A Discriminated Union (also called a tagged union) is a special kind of union that uses a common literal field to determine the shape of the rest of the object.

✅ Basic Example

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

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

type Shape = Circle | Square;

Now we can discriminate based on the kind field:

function getArea(shape: Shape): number {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.side ** 2;
  }
}

⚙️ Why Use Discriminated Unions?

They make your code:

✅ Type-safe

✅ Easier to reason about

✅ Extensible

✅ Great for Redux reducers, form handling, and state machines


🔄 Example: API Responses