Negation Narrowing with !
You'll learn how the ! operator helps TypeScript understand what types remain after you've explicitly checked for falsy values.
The Opposite Side of the Coin
You've already seen how truthiness checks narrow types by eliminating falsy possibilities. Negation narrowing works in reverse: when you write if (!value), TypeScript knows you're inside the falsy branch, and it narrows the type to match.
If a variable could be string | null, then !value doesn't just check for null — it checks for all falsy values (null, undefined, "", 0, false). Inside that if (!value) block, TypeScript knows the value must be one of those falsy types.
How It Works
function greet(name: string | null) {
if (!name) {
// TypeScript narrows name to: null
console.log("No name provided");
return;
}
// Here, name is narrowed to: string
console.log(`Hello, ${name.toUpperCase()}`);
}
When you negate with !, TypeScript performs the same truthiness analysis but inverts the narrowing. After the if (!name) guard returns or throws, control flow analysis knows that name cannot be falsy anymore.
Think of It as a Filter
Imagine sorting mail: truthiness checks (if (value)) put "real letters" in one pile. Negation checks (if (!value)) put "empty envelopes" in another. TypeScript tracks which pile you're looking at and adjusts what types are possible.
The ! operator is particularly useful for early returns or error handling — you handle the "nothing here" case first, then proceed confidently with the real value.
Key Takeaway: Using if (!value) narrows the type to falsy possibilities inside the block, and eliminates them afterward through control flow analysis.