TypeScript Reference ยท Narrowing and Type Guards
Truthiness narrowing in TypeScript
Reference for truthiness narrowing in TypeScript: how if (x), !, && and || remove null, undefined and falsy values, and the pitfalls with 0 and empty strings.
JavaScript treats some values as falsy in conditions: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy. TypeScript uses this to narrow: inside if (x) the type loses the members that can only be falsy, and in the else branch it keeps the ones that may be.
The check works with if, the ternary operator, !, && and ||. It is most often used to strip null and undefined from an optional value.
function len(s: string | null | undefined): number { if (s) { return s.length; // s: string } return 0; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
if (x) { /* x is truthy */ } else { /* x may be falsy */ } if (!x) { /* x may be falsy */ } x && x.prop x || fallback cond ? a : b
Narrowing rules:
| Declared type | In the truthy branch | In the falsy branch |
|---|---|---|
string | null |
string |
string | null (the string could be "") |
number | undefined |
number |
number | undefined (the number could be 0 or NaN) |
boolean | null |
true |
false | null |
object | null |
object |
null |
"a" | "b" |
"a" | "b" |
never |
Edge cases:
- Object types are always truthy, so the falsy branch of
T | nullfor an objectTis exactlynull(orundefined). - The literal types
0,""andfalseare narrowed precisely.
Usage notes
- 0, "" and NaN are falsy. If they are valid values, test explicitly with
!== undefined,!= nullor equality narrowing. ||versus??.a || breplaces any falsya.a ?? breplaces onlynullandundefined, so0and""survive.- Optional chaining.
user?.address?.cityis usually shorter than a chain of&&, and TypeScript narrows after it as well. - Strict null checks. Without
strictNullChecks,nullandundefinedare in every type, so truthiness narrowing has little to remove. Keepstricton. - Double negation.
!!xconverts tobooleanbut the result is justboolean; TypeScript still narrowsxwhen the expression is a condition. - Callbacks. A narrowing of a mutable variable does not survive into a function created later if the variable is reassigned.