0
0
Typescriptprogramming~5 mins

Discriminated unions in Typescript

Choose your learning style9 modes available
Introduction

Discriminated unions help you work with different types of data in one place safely. They let you tell which type you have by checking a special property.

When you have a variable that can hold different shapes of data, like a shape that can be a circle or a square.
When you want to write code that handles different cases clearly and safely without mistakes.
When you want TypeScript to help you catch errors by knowing exactly which type you are working with.
When you want to switch between different types and run different code for each type.
Syntax
Typescript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(shape: Shape) {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
  }
}

The kind property is the discriminant that tells TypeScript which type it is.

Use a switch or if to check the discriminant and handle each case.

Examples
This defines an animal that can be a dog or a cat, distinguished by the type property.
Typescript
type Animal =
  | { type: "dog"; barkVolume: number }
  | { type: "cat"; livesLeft: number };
Here we check the type to know if the animal is a dog or cat and use the right property.
Typescript
function speak(animal: Animal) {
  if (animal.type === "dog") {
    console.log(`Bark volume: ${animal.barkVolume}`);
  } else {
    console.log(`Lives left: ${animal.livesLeft}`);
  }
}
This models a response that can be success or error, using status as the discriminant.
Typescript
type Response =
  | { status: "success"; data: string }
  | { status: "error"; message: string };
Sample Program

This program defines a Vehicle type that can be a car or a bike. The describe function uses the kind property to know which type it is and returns a description. We create a car and a bike and print their descriptions.

Typescript
type Vehicle =
  | { kind: "car"; wheels: 4; brand: string }
  | { kind: "bike"; wheels: 2; hasBell: boolean };

function describe(vehicle: Vehicle) {
  switch (vehicle.kind) {
    case "car":
      return `Car brand: ${vehicle.brand}, wheels: ${vehicle.wheels}`;
    case "bike":
      return `Bike with bell: ${vehicle.hasBell}, wheels: ${vehicle.wheels}`;
  }
}

const myCar: Vehicle = { kind: "car", wheels: 4, brand: "Toyota" };
const myBike: Vehicle = { kind: "bike", wheels: 2, hasBell: true };

console.log(describe(myCar));
console.log(describe(myBike));
OutputSuccess
Important Notes

Always use a unique string literal property as the discriminant for clear type checking.

Discriminated unions make your code safer by letting TypeScript know exactly which type you are working with.

Summary

Discriminated unions use a special property to tell types apart.

They help write clear and safe code when working with multiple types.

Use switch or if to check the discriminant and handle each case.