AI Hints
TypeScript · Lesson 32 of 120

Truthiness and Equality

More narrowing.

⏱ 2 min read▶ Video at 25:27🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Other checks narrow types too. An if on a value removes null and undefined. Comparing with equals narrows to the matching type.

Truthiness and Equality
From the video: Truthiness and Equality
  • if (x)
  • === comparisons
  • Both narrow

Narrowing by checks

Coupon might be a string, null, or undefined. The if removes null and undefined, so it's a string inside. Then comparing to a fixed value narrows it even further. Run it.

app.tstypescript
function discount(coupon: string | null | undefined): number {
  if (!coupon) {
    return 0;
  }
  if (coupon === "SAVE10") {
    return 10;
  }
  return coupon.length > 6 ? 5 : 0;
}

console.log(discount(null), discount("SAVE10"), discount("WELCOME2026"));
Output
0 10 5

Watch out

An empty string and zero are also false. So checking if a count is truthy treats zero like missing. When zero is a valid value, compare with null directly instead.

keyvalue
""falsy
0falsy
Count of 0use != null
x != nullremoves null and undefined

Summary

If checks and comparisons narrow types, but remember that zero and empty strings are falsy. Next, the in operator.

Key takeaways
  • if (!x)
  • ===
  • Careful with 0
Next up: The in Operator — which shape?