0
0
Typescriptprogramming~3 mins

Why Discriminated union narrowing 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 working with, without guesswork?

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 checks and guesswork to figure it out.

The Problem

Manually checking each shape's properties is slow and confusing. You might forget a case or make mistakes, causing bugs. The code becomes long and hard to read, making it painful to maintain.

The Solution

Discriminated union narrowing lets you tag each shape with a unique label. This way, TypeScript can automatically know which shape you have and let you write simple, clear code that handles each case safely and easily.

Before vs After
Before
if (shape.radius !== undefined) { /* handle circle */ } else if (shape.side !== undefined) { /* handle square */ }
After
switch (shape.kind) { case 'circle': /* handle circle */ break; case 'square': /* handle square */ break; }
What It Enables

This concept makes your code safer and easier to understand by clearly distinguishing types and letting the computer help you handle each case correctly.

Real Life Example

Think of a drawing app that needs to process different shapes. Using discriminated unions, it can quickly decide how to draw each shape without errors or complicated checks.

Key Takeaways

Manual type checks are slow and error-prone.

Discriminated unions tag types for easy identification.

TypeScript narrows types automatically for safer code.