Discover how a simple check can save your code from confusing bugs!
Why Type narrowing with typeof in Typescript? - Purpose & Use Cases
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.
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.
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.
function process(value: any) {
// No type check
console.log(value.toFixed(2));
}function process(value: unknown) {
if (typeof value === 'number') {
console.log(value.toFixed(2));
}
}It enables writing safer and clearer code that adapts to different data types without errors.
When building a calculator app, you might get inputs as numbers or strings. Using typeof helps you handle each input correctly, avoiding crashes.
Manual type guessing is slow and risky.
typeof checks the type clearly and safely.
Type narrowing helps your code handle data correctly.