0
0
Typescriptprogramming~3 mins

Why Type narrowing with typeof in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple check can save your code from confusing bugs!

The Scenario

Imagine you have a box with different kinds of fruits mixed together. You want to pick only the apples, but you have to check each fruit by guessing its type without any clear label.

The Problem

Without a clear way to check the type, you might pick the wrong fruit or waste a lot of time guessing. This is like writing code that treats all data the same, causing errors or unexpected results.

The Solution

Type narrowing with typeof lets you check the exact type of a value before using it. This way, your code knows what to expect and can handle each type correctly and safely.

Before vs After
Before
function process(value: any) {
  // No type check
  console.log(value.toFixed(2));
}
After
function process(value: unknown) {
  if (typeof value === 'number') {
    console.log(value.toFixed(2));
  }
}
What It Enables

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

Real Life Example

When building a calculator app, you might get inputs as numbers or strings. Using typeof helps you handle each input correctly, avoiding crashes.

Key Takeaways

Manual type guessing is slow and risky.

typeof checks the type clearly and safely.

Type narrowing helps your code handle data correctly.