What You'll Learn
You'll learn how to use typeof checks to separate booleans from other types in a union, enabling TypeScript to treat your value as a true boolean.
The Core Idea
When you have a value that could be a boolean or something else (like a number or string), TypeScript needs help understanding when it's specifically a boolean. By checking typeof myValue === 'boolean', you tell TypeScript: "Inside this code block, I know for certain this is a boolean."
This is the same pattern you used with typeof 'number', but now applied to booleans.
How It Works
The typeof operator in JavaScript returns the string 'boolean' for both true and false. TypeScript recognizes this check and narrows the type:
function describe(value: number | boolean): string {
if (typeof value === 'boolean') {
// TypeScript knows: value is boolean here
return value ? 'yes' : 'no';
}
// TypeScript knows: value is number here
return value.toFixed(2);
}
Before the if check, value could be either type. After the check passes, TypeScript understands you're working with a boolean, so boolean-specific operations (like using it in a ternary) are safe.
Why This Matters
Booleans often appear in unions with other primitives, especially when handling configuration values or API responses that might return flags or numeric status codes. The typeof guard lets you handle each case appropriately.
Key Takeaway: Use typeof value === 'boolean' to narrow union types containing booleans, giving you type-safe access to boolean-specific logic inside the guarded block.