What it is and why to use it
A truthiness condition rejects values such as zero, an empty string, false, null and undefined. That is useful only when all those values should take the same path. An explicit missing-value check is clearer when zero or an empty string is a valid value.
Common mistakes and limitations
Do not use a broad truthiness guard when valid empty values must be preserved. Null and undefined may need different policies. Conversely, a non-empty string such as "false" is truthy even though its text describes a boolean concept.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
if (value !== undefined) { /* preserves zero */ }Examples
Truthiness versus Explicit Missing-Value Checks
Standalone TypeScript 5.8+ example; expected output is explained below.
function describeCount(count: number | undefined): string {
if (count === undefined) return "Not measured";
return "Count: " + count;
}
console.log(describeCount(0));
console.log(describeCount(undefined));- The missing case is checked directly instead of using if (!count).
- Zero reaches the measured-value branch and is displayed accurately.
- undefined is described separately. This distinction matters in reports where a measured zero and missing data mean different things.
- Expected output: Count: 0 Not measured
Best practices
- Do not use a broad truthiness guard when valid empty values must be preserved. Null and undefined may need different policies. Conversely, a non-empty string such as "false" is truthy even though its text describes a boolean concept.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook