Truthiness in Boolean Contexts
What You'll Learn
You'll learn how the logical operators && and || preserve or narrow types based on truthiness, giving you smarter type checking in compound expressions.
How && and || Work with Types
In JavaScript, && and || don't just return true or false—they return one of the actual values being compared. TypeScript understands this and uses it to narrow types intelligently.
The && Operator
When you use &&, TypeScript knows:
- If the left side is falsy, the whole expression has that left type
- If the left side is truthy, the expression has the right type
function processValue(value: string | null) {
const result = value && value.toUpperCase();
// result is: string | null
// If value is null, result is null
// If value is a string, result is string
}
The || Operator
With ||, TypeScript understands:
- If the left side is truthy, the expression has that left type
- If the left side is falsy, the expression has the right type
function getDefault(input: string | undefined) {
const output = input || "default";
// output is: string
// TypeScript knows undefined is falsy, so we get string either way
}
Practical Example
function greet(name: string | null) {
const greeting = name && `Hello, ${name}`;
// greeting is: string | null
}
Key Takeaway: TypeScript tracks types through && and || based on truthiness, giving you the correct union type for each branch of the expression—the left type when it might be returned, the right type when it might be returned, or a union of both.