0
0
Typescriptprogramming~3 mins

Why type narrowing is needed in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your code could instantly know exactly what kind of data it's handling, avoiding bugs before they happen?

The Scenario

Imagine you have a box that can hold different kinds of toys, but you don't know which toy is inside until you open it. You want to play with the toy, but you must first check what type it is to avoid breaking it or playing the wrong way.

The Problem

If you try to play with the toy without checking its type, you might use the wrong method or action, causing errors or crashes. Manually checking every possible type with many if-else statements is slow, confusing, and easy to get wrong.

The Solution

Type narrowing helps by automatically telling you what kind of toy is inside the box at each step. It lets you safely use the right actions without guessing or writing extra checks everywhere.

Before vs After
Before
function play(toy: string | number) {
  if (typeof toy === 'string') {
    console.log(toy.toUpperCase());
  } else {
    console.log(toy.toFixed(2));
  }
}
After
function play(toy: string | number) {
  if (typeof toy === 'string') {
    console.log(toy.toUpperCase()); // TypeScript knows toy is string here
  } else {
    console.log(toy.toFixed(2)); // TypeScript knows toy is number here
  }
}
What It Enables

It enables writing safer and clearer code that adapts automatically to different data types without mistakes.

Real Life Example

When building a chat app, messages can be text or images. Type narrowing helps the app know when to show text or display an image, avoiding crashes or wrong displays.

Key Takeaways

Manual type checks are slow and error-prone.

Type narrowing automatically detects the exact type in each code branch.

This leads to safer, cleaner, and more reliable code.