Comparing Against Literal Values
You'll learn how comparing against specific literal values narrows string literal union types down to a single, precise type.
The Core Idea
When you have a variable that could be one of several literal values (a union like "left" | "right" | "center"), TypeScript doesn't initially know which one it is. But the moment you write a check like if (direction === "left"), TypeScript is smart enough to realize that inside that if-block, the variable can only be "left" — it's been narrowed from three possibilities to exactly one.
This is powerful because TypeScript now treats your variable as that single literal type, giving you certainty and preventing errors.
How It Works
type Direction = "left" | "right" | "center";
function move(direction: Direction) {
// direction is "left" | "right" | "center" here
if (direction === "left") {
// direction is narrowed to ONLY "left" here
console.log("Moving left");
}
if (direction === "right") {
// direction is narrowed to ONLY "right" here
console.log("Moving right");
}
// direction is still "left" | "right" | "center" here
}
The === comparison acts like a filter. TypeScript's control flow analysis sees "if this equals this exact value, then it must be that type in this block."
The Analogy
Think of sorting mail into specific bins. You start with a pile labeled "letters or packages or postcards." When you check if (item === "letter"), you're reaching into the letter-only bin — you know exactly what you're handling.
Key Takeaway: Comparing against literal values with === narrows union types to the exact literal being checked, giving you type precision within that conditional block.