Truthiness Narrowing with Unions
What you'll learn: How to use simple if (value) checks to eliminate null and undefined from union types.
The Core Idea
When you have a union type that includes null or undefined, TypeScript lets you narrow it down using JavaScript's built-in "truthiness" checks. Since null and undefined are falsy values, an if (value) statement tells TypeScript: "Inside this block, value can't be null or undefined anymore."
How It Works
When you write:
function greet(name: string | null) {
if (name) {
console.log(name.toUpperCase()); // TypeScript knows name is string here
}
}
TypeScript's control flow analysis sees the if (name) check and realizes:
- If execution enters the
ifblock,namemust be truthy nullis falsy, so it's been eliminated- Therefore,
namemust bestringinside the block
This works with undefined too:
function processInput(input: string | undefined) {
if (input) {
return input.trim(); // Safe: input is definitely string
}
return "default";
}
Why This Matters
This pattern is especially powerful with optional properties or nullable return values. It's a clean, JavaScript-native way to handle "might be missing" scenarios without verbose type guards.
Key Takeaway: Using if (value) automatically narrows union types by removing null and undefined, letting you safely access properties and methods on the remaining type.