Type Guards for Primitives
What you'll learn: How to use typeof to safely narrow down primitive union types at runtime.
The Problem with Union Types
When you have a variable that could be one of several primitive types (a union), TypeScript doesn't know which type it actually is until you check. That's where type guards come in—they're runtime checks that tell TypeScript "I've verified what this is now, so treat it accordingly."
Using typeof to Narrow Types
The typeof operator is your primary tool for narrowing primitive unions. When you check typeof value === "string", TypeScript understands that inside that if block, the value must be a string.
function processValue(value: string | number) {
if (typeof value === "string") {
// TypeScript knows value is string here
console.log(value.toUpperCase());
} else {
// TypeScript knows value is number here
console.log(value.toFixed(2));
}
}
How TypeScript Follows Your Logic
TypeScript analyzes your typeof checks and narrows the type automatically. Each branch gets its own refined type. This is called control flow analysis—TypeScript traces through your if/else statements to determine what's possible where.
let mixed: boolean | null | undefined;
if (typeof mixed === "boolean") {
// mixed is boolean here
} else if (mixed === null) {
// mixed is null here
} else {
// mixed is undefined here
}
Key Takeaway: Use typeof checks to narrow primitive union types at runtime, allowing TypeScript to safely unlock type-specific operations in each branch.