Sub topic 4
Truthiness Narrowing and Its Pitfalls
Assume you know basic TypeScript control flow, union types, and strictNullChecks. This chapter focuses on how TypeScript uses JavaScript truthiness to narrow a value inside an if, ternary expression, or logical expression.
How truthiness narrowing works
A truthy value behaves like true in a condition. A falsy value behaves like false. In JavaScript, common falsy values include:
false0""nullundefinedNaN
TypeScript uses this runtime rule during control flow analysis. For example, a check against null and undefined can remove those members from a union:
function describeCount(count: number | null | undefined): string {
if (count) {
return `Count: ${count.toFixed(0)}`;
}
return "No count";
}
console.log(describeCount(4));
console.log(describeCount(null));Inside the first branch, count is known to be a number. However, the check also rejects 0. Therefore, describeCount(0) returns "No count", even though zero is a valid number.
This table shows the difference between a value's type and its truthiness:
| Value | Type | Truthy? |
|---|---|---|
| `42` | `number` | Yes |
| `0` | `number` | No |
| `"hello"` | `string` | Yes |
| `""` | `string` | No |
| `null` | `null` | No |
When truthiness is useful
Truthiness is convenient when every falsy value means “missing” or “invalid.” It works well for optional objects:
type Settings = {
theme: string;
};
function themeName(settings: Settings | null): string {
if (!settings) {
return "default";
}
return settings.theme;
}
console.log(themeName({ theme: "dark" }));
console.log(themeName(null));It can also simplify checks for optional strings when an empty string should count as absent:
function greeting(name?: string): string {
return name ? `Hello, ${name}` : "Hello, stranger";
}The main pitfall: valid falsy values
Do not use a broad truthiness check when zero, an empty string, or false is a valid value.
Use an explicit comparison when you only want to reject null or undefined:
function formatScore(score: number | null | undefined): string {
if (score == null) {
return "No score";
}
return `Score: ${score}`;
}
console.log(formatScore(0));
console.log(formatScore(null));The comparison value == null is a deliberate exception to the usual preference for strict equality. It matches both null and undefined, but not 0, "", or false.
If only one value should be rejected, use strict equality:
function label(enabled: boolean | undefined): string {
if (enabled === undefined) {
return "Unknown";
}
return enabled ? "Enabled" : "Disabled";
}Truthiness and compound conditions
Logical operators also trigger narrowing:
function uppercaseName(name: string | undefined): string | undefined {
return name && name.toUpperCase();
}When name is an empty string, this returns "", not undefined. The expression preserves the falsy left-hand value. This behavior is often useful, but it can surprise readers.
Prefer a clear condition when the distinction matters:
function uppercasePresentName(name: string | undefined): string | undefined {
if (name === undefined) {
return undefined;
}
return name.toUpperCase();
}Exercise
Why should score == null be preferred over if (!score) when a score of zero is valid?
Show answer
if (!score) treats 0 as falsy and sends it to the missing-value branch. score == null matches only null and undefined, so zero remains a valid score.