Narrowing with !== and !==
What you'll learn: How to use strict and loose inequality operators to eliminate null or undefined from union types.
Just like you can narrow types by checking equality with === and ==, you can also narrow by checking inequality with !== and !=. This is especially useful when you want to handle the case where a value is not null or not undefined.
The Core Idea
When you check that a variable is !== null or !== undefined, TypeScript understands that inside the if block (or after the check), that value cannot be null or undefined anymore. TypeScript removes those types from the union.
The same principle applies in the else branch—if you check x !== null, TypeScript knows that in the else branch, x must be null.
How It Works
function greet(name: string | null) {
if (name !== null) {
// name is narrowed to string here
console.log(name.toUpperCase());
} else {
// name is narrowed to null here
console.log("No name provided");
}
}
You can also use the loose inequality != to check for both null and undefined at once:
function display(value: string | null | undefined) {
if (value != null) {
// value is narrowed to string here
console.log(value.length);
}
}
This works because value != null is true when value is neither null nor undefined.
Why This Matters
Inequality narrowing lets you write defensive code that handles missing values gracefully, while TypeScript ensures you only access properties when they're safe to use.
Key Takeaway: Using !== and != eliminates null or undefined from union types, allowing you to safely work with the remaining type in both the if and else branches.