What if your code could instantly know exactly what kind of data it's handling, avoiding bugs before they happen?
Why type narrowing is needed in Typescript - The Real Reasons
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.
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.
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.
function play(toy: string | number) {
if (typeof toy === 'string') {
console.log(toy.toUpperCase());
} else {
console.log(toy.toFixed(2));
}
}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
}
}It enables writing safer and clearer code that adapts automatically to different data types without mistakes.
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.
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.