Interview Q&A / TypeScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the pitfall of narrowing with a truthiness check in TypeScript?

SHORT ANSWER

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

ts
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 kept

What 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.

#narrowing#pitfalls

Related questions

Practise more TypeScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open TypeScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.