What is the pitfall of narrowing with a truthiness check in TypeScript?
if (x) removes null and undefined but also removes valid falsy values: 0, an empty string, false and NaN. For a number or string that could legitimately be empty, check against null and undefined explicitly.
Explain it simply
A shop billing screen has a quantity field. If the user types 0, that is a real answer. If the code says if (qty), zero is treated like "nothing entered" and skipped.
TypeScript narrows correctly here: inside if (qty) the type is number. The compiler is fine. The bug is in the logic, because the check throws away more than you meant. The safe check for "present" is qty !== undefined (or != null to cover both).
Example
function label(qty: number | undefined): string {
if (qty) return `Qty: ${qty}`; // skips 0
return "Not entered";
}
console.log(label(0)); // Output: Not entered (wrong!)
function labelFixed(qty: number | undefined): string {
if (qty !== undefined) return `Qty: ${qty}`;
return "Not entered";
}
console.log(labelFixed(0)); // Output: Qty: 0
const name = "" ;
const shown = name || "Guest"; // "" falls to "Guest"
const kept = name ?? "Guest"; // "" is keptWhat to say in the interview
"Truthiness narrowing is correct for TypeScript but loose for logic: it also drops 0, empty strings and false. When those are valid values I compare to undefined or null directly, and I use ?? instead of || for defaults."
Common mistakes
- Using || for defaults when 0 or an empty string is acceptable input.