typeof Guard
In this page:
Checking Strings
The typeof operator returns the literal string "string" when applied to a string value, and checking specifically for that result is enough for TypeScript to narrow a union type down to string. Inside that narrowed branch, every string method becomes safely available.
Example: Checking Strings
function process(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
process("hello");
Checking Numbers
typeof returns "number" for values of the number type, and guarding on that result lets TypeScript safely permit number-specific operations and methods, like toFixed, that wouldn't be safe on other members of a union.
Example: Checking Numbers
function process(value: string | number) {
if (typeof value === "number") {
console.log(value.toFixed(2));
}
}
process(3.14159);
Checking Booleans
typeof returns "boolean" for both true and false values, making it a reliable guard whenever boolean values are mixed into a union or when processing genuinely unknown input from an external source. It cleanly separates boolean handling from every other possible type.
Example: Checking Booleans
function process(value: boolean | string) {
if (typeof value === "boolean") {
console.log(value ? "Yes" : "No");
}
}
process(true);
Checking Functions
The typeof operator returns "function" specifically for values that can actually be called. This lets you safely verify that an unknown or union-typed value is callable before invoking it, avoiding a runtime TypeError from calling something that isn't a function.
Example: Checking Functions
function run(value: unknown) {
if (typeof value === "function") {
value();
}
}
run(() => console.log("Called!"));
Checking Multiple Types
Multiple typeof checks can be chained together, typically with else-if branches, to handle several possible primitive types within one function. This is especially useful when a function is designed to accept a broad union of primitives, or even an unknown value, and needs to branch its behavior for each case.
Example: Checking Multiple Types
function describe(value: string | number | boolean) {
if (typeof value === "string") {
console.log("String:", value);
} else if (typeof value === "number") {
console.log("Number:", value);
} else if (typeof value === "boolean") {
console.log("Boolean:", value);
}
}
describe(42);
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: