TypeScript · Lesson 32 of 120
Truthiness and Equality
More narrowing.
Other checks narrow types too. An if on a value removes null and undefined. Comparing with equals narrows to the matching type.

- 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.
| key | value |
|---|---|
| "" | falsy |
| 0 | falsy |
| Count of 0 | use != null |
| x != null | removes 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?