Non-null Assertion with Truthiness
What you'll learn: How to use truthiness checks to eliminate null from union types, and when this technique can backfire.
When you have a value typed as string | null, TypeScript doesn't know if it's safe to use. But if you check if (x), TypeScript narrows the type to string inside the block — because null is falsy, so it must be a string if the condition passed.
How It Works
function greet(name: string | null) {
if (name) {
// TypeScript knows: name is string here
console.log(name.toUpperCase());
}
}
The if (name) check eliminates null from the type. TypeScript's control flow analysis sees that null is falsy, so if the condition is true, name must be a string.
The Empty String Pitfall
Here's the trap: empty string ("") is also falsy. If your logic treats empty strings as valid data, truthiness narrowing will incorrectly exclude them:
function processInput(input: string | null) {
if (input) {
console.log(`Processing: ${input}`);
}
// Empty string "" gets skipped!
}
processInput(""); // Nothing happens — bug!
If "" is a legitimate value in your application, use an explicit null check instead:
if (input !== null) {
// Now "" is correctly included
console.log(`Processing: ${input}`);
}
Key Takeaway: Truthiness checks (if (x)) successfully narrow away null, but they also exclude empty strings. Use explicit !== null checks when empty string is valid data.