Truthiness narrowing — if (value) also drops 0 and ""¶
Level: 201 · for TypeScript users who test for null with if (value)
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: if (count) narrows number | null to number, which reads as 'not null', but at run time 0 fails the test too: label(0) prints no count, and only the type after the if, still number | null, hints that a number can arrive there.
Keywords: truthiness narrowing
What the finished page will answer¶
- What does
label(0)print when the function testsif (count), and what types doescounthave inside and after theif? - For
flag: 0 | 1 | null, what are the types in the true and the false branch, and why can the checker be exact there? - Which values fail
if (x), and which of them can a type name:0,-0,0n,"",NaN,null,undefined,false? - Which test keeps
0and"":x != null,x !== null && x !== undefined, orx ?? fallback? - Why does
!!xnarrow in TypeScript 7.0.2 whileBoolean(x)does not?
Examples it will need¶
-
truthiness_narrowing_zero_sh.sh— the narrowed types in both branches, printed by tsc through deliberate errors, then Node labelling 3, 0 and null -
truthiness_narrowing_literal_union_tserror.ts— the types1and0 | nullthat tsc gives the two branches ofif (flag) -
truthiness_narrowing_not_null_ts.ts— the same labels computed withcount !== null, where 0 is reported as a count
See also¶
- Truthy and falsy — the short list of values
iftreats as false ?.and??— the??default that keeps0- Narrowing — the other tests the checker understands
- Short-circuit evaluation — the
&&and||operators, which narrow the same way - Rust: Meet the
bool↗ — no truthiness in Rust:if countdoes not compile - Rust: Six kinds of zero ↗ — keeping zero and missing apart as different values, in Rust