Equality Narrowing with ===
What you'll learn: How strict equality checks eliminate specific branches from union types, giving you precise type information.
The Core Idea
When you compare a union-typed value against a specific literal using ===, TypeScript eliminates the branches that could never match. This is called equality narrowing.
For example, if a variable could be string | null, checking x === null tells TypeScript: "Inside this if-block, x is definitely null." In the else-block, TypeScript knows x must be string because the null case was already handled.
Think of it like sorting mail: if you check "is this package labeled 'fragile'?", you've split your packages into two piles — fragile ones (where the answer is yes) and non-fragile ones (where the answer is no).
How It Works
function printId(id: string | null) {
if (id === null) {
console.log("No ID provided");
// Inside here, id is narrowed to: null
} else {
console.log(id.toUpperCase());
// Inside here, id is narrowed to: string
}
}
The === check acts as a type guard. TypeScript sees the comparison and updates what it knows about id in each branch.
You can also check against specific literal values:
type Status = "pending" | "success" | "error";
function handle(status: Status) {
if (status === "success") {
// status is exactly "success" here
}
}
Key Takeaway: Using === against a literal value narrows union types by eliminating impossible branches, giving you type-safe access to specific properties and methods in each code path.