Narrowing with typeof 'number'
What you'll learn: How to use typeof to distinguish numbers from other types, and understand TypeScript's special handling of NaN.
The Core Idea
When you check typeof value === 'number', TypeScript narrows the type to number. This is especially useful inside union types where a value could be a number or something else. After the check, TypeScript knows the value is definitely a number in that code branch.
How It Works
function processValue(value: string | number) {
if (typeof value === 'number') {
// TypeScript knows: value is number here
const doubled = value * 2;
} else {
// TypeScript knows: value is string here
const upper = value.toUpperCase();
}
}
Inside the if block, TypeScript has narrowed value from string | number down to just number, so you can safely use math operations.
The NaN Gotcha
Here's something tricky: NaN (Not a Number) actually has typeof NaN === 'number' in JavaScript. This means TypeScript's narrowing will treat NaN as a valid number:
const result: string | number = NaN;
if (typeof result === 'number') {
// result could be NaN here!
// TypeScript thinks it's safe, but NaN behaves strangely in math
}
If you need to exclude NaN, you must add an additional check using Number.isNaN() after the typeof guard.
Key Takeaway: The typeof value === 'number' guard narrows a union type to number, but remember that NaN technically counts as a number in JavaScript, so additional validation may be needed for strict numeric operations.