What You'll Learn
You'll learn how to use negative typeof checks (like !==) to eliminate types from a union, narrowing to what's left.
The Core Idea
So far you've used typeof to narrow to a specific type (typeof x === 'string'). But you can also use it to narrow away from a type using !== or !=.
When TypeScript sees typeof x !== 'string', it thinks: "Inside this branch, x can't be a string anymore—so it must be one of the other types in the union."
This is especially useful when you want to handle "everything except X" in a clean way.
Plain English
Think of a union like a group of suspects. Using typeof x === 'string' is like saying "you're the string!" and pulling that suspect aside. Using typeof x !== 'string' is like saying "everyone except the string, step forward." TypeScript automatically eliminates the string type and narrows to the remaining possibilities.
How It Works in Practice
If you have a variable that could be string | number | boolean, and you write:
if (typeof value !== 'string') {
// TypeScript knows: value is number | boolean here
}
TypeScript removes string from the union, leaving only number | boolean. You can chain multiple negated checks to keep eliminating types until you're left with exactly what you need.
Why This Matters
Negated checks give you another tool for type narrowing. Sometimes it's clearer to say "if it's not a string, do this" rather than listing out every other type explicitly. It keeps your code concise and intention-revealing.
Key Takeaway: typeof x !== 'type' narrows a union by eliminating that type, leaving TypeScript to infer what remains—giving you precise control over complex unions with clean, readable logic.