Sub topic 4
Truthiness narrowing and its pitfalls
This chapter assumes you know basic TypeScript syntax, union types such as string | number, and JavaScript if statements, &&, ||, and the ternary operator. You should also have read the earlier chapters on how control flow analysis narrows a union inside a branch.
What truthiness narrowing is
JavaScript converts any value to a boolean when it appears in a condition. A value that converts to false is called falsy. Every other value is truthy. TypeScript follows this rule when it narrows. If a condition tests a value directly, TypeScript removes the types that can never be truthy from the true branch, and removes the types that can never be falsy from the false branch.
The falsy values in JavaScript are:
false0and-00n(the zero BigInt)""(the empty string)nullundefinedNaN
Everything else is truthy. This includes "0", "false", [], {}, and any function.
The most common use is removing null and undefined from a union:
function shorten(text: string | null | undefined): string {
if (text) {
// text is string here
return text.slice(0, 10);
}
// text is string | null | undefined here
return "";
}Inside the if, text is string. TypeScript removed null and undefined because neither is truthy. In the false branch, the type stays string | null | undefined, because the empty string "" is a string that is falsy.
Where truthiness checks work
Truthiness narrowing is not limited to if. TypeScript applies it in every place JavaScript evaluates a condition:
if,while, andforconditions- The ternary operator
a ? b : c - The
!operator, including the double negation!!value - The
&&and||operators - The
??=,&&=, and||=assignment operators
Here is a short example using && and the ternary operator:
function lengthOrZero(text: string | undefined): number {
return text && text.length > 0 ? text.length : 0;
}
function label(count: number | undefined): string {
return count ? `${count} items` : "no items";
}In lengthOrZero, the right side of && runs only when text is truthy, so text.length is safe. In label, the true branch sees count as number and the false branch sees number | undefined.
Narrowing with early returns
Control flow analysis also understands early exits. A negated check followed by return, throw, or continue narrows everything after it:
function firstWord(sentence: string | undefined): string {
if (!sentence) {
return "";
}
// sentence is string from here on
return sentence.split(" ")[0];
}This guard-clause style keeps the main logic unindented and is the form most codebases prefer.
Pitfall 1: falsy values that are valid data
Truthiness checks do not only remove null and undefined. They also reject 0, "", NaN, and 0n. If those are legitimate values in your domain, a truthiness check hides a bug. The compiler does not warn you, because the code is valid.
function formatQuantity(quantity: number | undefined): string {
if (!quantity) {
return "unknown";
}
return `${quantity} units`;
}
console.log(formatQuantity(5)); // "5 units"
console.log(formatQuantity(undefined)); // "unknown"
console.log(formatQuantity(0)); // "unknown" (wrong)A quantity of zero is real data, yet the function reports it as unknown. The fix is to check for the missing value explicitly:
function formatQuantity(quantity: number | undefined): string {
if (quantity === undefined) {
return "unknown";
}
return `${quantity} units`;
}Now 0 produces "0 units". The next chapter covers equality checks and null handling in detail.
The same problem appears with strings. An empty string is often a valid value, such as an optional suffix or a cleared text field. Use value === undefined or value == null when you mean "missing", and use a truthiness check only when you really want to treat empty values the same as missing ones.
Pitfall 2: the false branch is wider than you expect
Truthiness narrowing removes types in the true branch, but the false branch keeps every type that can be falsy. For a string, that means the false branch is still string, not "". TypeScript does narrow some types in the false branch. Consider these cases:
| Declared type | Type in the true branch | Type in the false branch | Column | Column |
|---|---|---|---|---|
| `string \ | undefined` | `string` | `string \ | undefined` |
| `number \ | null` | `number` | `number \ | null` |
| `boolean` | `true` | `false` | ||
| `boolean \ | undefined` | `true` | `boolean \ | undefined` |
| `object \ | null` | `object` | `null` |
Types such as object, functions, and class instances are always truthy, so they drop out of the false branch. Primitive types such as string, number, and bigint can be falsy, so they stay.
This matters when you write an else branch and expect the value to be only null or undefined. For primitives, it can still hold 0 or "".
function describe(value: string | null): string {
if (value) {
return value;
}
// value is string | null here, not just null
return value === null ? "missing" : "empty";
}Pitfall 3: `||` replaces valid falsy values
The || operator returns its right side whenever the left side is falsy. Used for defaults, it overwrites 0, "", and false:
interface Options {
retries?: number;
prefix?: string;
}
function resolve(options: Options): { retries: number; prefix: string } {
return {
retries: options.retries || 3, // 0 becomes 3
prefix: options.prefix || "log", // "" becomes "log"
};
}
console.log(resolve({ retries: 0, prefix: "" }));
// { retries: 3, prefix: 'log' }The types are correct, so TypeScript raises no error, but the caller asked for zero retries and got three. The nullish coalescing operator ?? replaces only null and undefined:
function resolve(options: Options): { retries: number; prefix: string } {
return {
retries: options.retries ?? 3,
prefix: options.prefix ?? "log",
};
}With ??, the call resolve({ retries: 0, prefix: "" }) keeps both values. Prefer ?? for defaults unless you want to treat all falsy values as missing.
Pitfall 4: objects and arrays are always truthy
Empty arrays and empty objects are truthy. A check like if (items) does not test whether an array has elements:
function firstItem(items: string[] | undefined): string {
if (items) {
// items is string[], but it may be empty
return items[0]; // undefined at runtime for []
}
return "none";
}To test for content, check the length explicitly:
function firstItem(items: string[] | undefined): string {
if (items && items.length > 0) {
return items[0];
}
return "none";
}Note that with the default compiler settings, items[0] has type string even though the element might not exist. The compiler option noUncheckedIndexedAccess changes this so indexed reads include undefined. It is worth enabling if you rely on this pattern.
Pitfall 5: narrowing `boolean` and literal types
Truthiness narrowing also works on literal types. The type boolean is the union true | false, so a truthiness check splits it. A union of string literals that includes "" splits the same way:
type Mode = "" | "fast" | "safe";
function run(mode: Mode): string {
if (mode) {
return mode; // "fast" | "safe"
}
return "default"; // mode is ""
}Here the false branch is exactly "", because the only falsy member of the union is the empty string literal.
Pitfall 6: `!!` does not narrow when stored
The double negation !!value converts a value to a boolean. TypeScript narrows when !!value appears directly in a condition. If you store the result in a variable that has an explicit boolean type, the connection to the original value is lost in many cases:
function process(value: string | undefined): string {
const hasValue: boolean = !!value;
if (hasValue) {
return value.toUpperCase(); // error in older compiler versions
}
return "";
}Whether this compiles depends on your TypeScript version and on whether the const has a type annotation. Recent versions can track a condition stored in a const without annotation, but the safest approach is to test the value in the if itself:
function process(value: string | undefined): string {
if (value) {
return value.toUpperCase();
}
return "";
}Choosing between truthiness and equality
The decision depends on which values you want to reject.
| Goal | Check | Rejects | Column | Column |
|---|---|---|---|---|
| Reject only missing values | `value == null` or `value === undefined` | `null`, `undefined` | ||
| Reject missing values and empty strings | `value` (truthiness) on a `string \ | undefined` | `null`, `undefined`, `""` | |
| Reject missing values and zero | `value` on a `number \ | undefined` | `null`, `undefined`, `0`, `NaN` | |
| Provide a default for missing values only | `value ?? fallback` | `null`, `undefined` | ||
| Provide a default for any falsy value | `value \ | \ | fallback` | all falsy values |
Summary of key points
- A truthiness check removes
null,undefined, and the falsy members of literal unions from the true branch. - The false branch keeps every primitive type that can be falsy, so it is usually wider than you expect.
0,"",NaN, and0nare falsy and are often valid data.- Use
??instead of||for defaults. - Empty arrays and objects are truthy. Check
lengthwhen you need to know if an array has items. - Put the check directly in the condition so the compiler can follow it.
Exercise
The function below should return the discount percentage, with 0 meaning "no discount". Callers sometimes pass 0 and sometimes undefined for an unknown discount. Find the bug and rewrite the function so that 0 gives "0% off" and undefined gives "no discount info".
function discountText(percent: number | undefined): string {
return percent ? ${percent}% off : "no discount info";
}
Show answer
The truthiness check treats 0 as missing, so discountText(0) returns "no discount info". Compare with undefined explicitly:
function discountText(percent: number | undefined): string {
return percent !== undefined ? ${percent}% off : "no discount info";
}
Now 0 gives "0% off", and undefined gives "no discount info". In the true branch, percent is still narrowed to number.
Exercise
What is the type of value in the false branch of if (value) { ... } else { ... } when value is declared as string | null, and why?
Show answer
It is string | null. The true branch removes null because null is never truthy. The false branch cannot remove string, because the empty string "" is a string that is falsy. So both null and "" can reach the else branch.
Exercise
A config reader uses const port = config.port || 8080; where config.port is number | undefined. A user sets the port to 0 to let the operating system pick a free port. What happens, and what is the fix?
Show answer
0 is falsy, so || replaces it with 8080 and the user's setting is ignored. Use the nullish coalescing operator: const port = config.port ?? 8080;. It replaces only null and undefined, so 0 is kept.