0
0
Typescriptprogramming~3 mins

Why Discriminated unions in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could instantly know exactly what kind of data it's dealing with, avoiding costly mistakes?

The Scenario

Imagine you have different types of shapes like circles and squares, and you want to write code that handles each shape differently. Without a clear way to tell which shape you have, you might write many if-else checks scattered everywhere.

The Problem

This manual approach is slow and confusing. You might forget a case, mix up properties, or write repetitive code. It's easy to make mistakes and hard to maintain as your program grows.

The Solution

Discriminated unions let you tag each shape with a unique label. This way, TypeScript knows exactly which shape you have and what properties it has. Your code becomes cleaner, safer, and easier to understand.

Before vs After
Before
if (shape.type === 'circle') {
  // handle circle
} else if (shape.type === 'square') {
  // handle square
}
After
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;
  }
}
What It Enables

It enables writing clear, error-free code that safely handles different data types with confidence.

Real Life Example

Think of a messaging app where messages can be text, images, or videos. Discriminated unions help you handle each message type correctly without confusion.

Key Takeaways

Manual type checks are error-prone and messy.

Discriminated unions tag data with unique labels for clarity.

This leads to safer, cleaner, and easier-to-maintain code.