typeof Guards with unknown
What you'll learn: How to safely narrow the unknown type to specific primitives like string, number, or boolean using typeof checks.
The Problem with unknown
You've learned that unknown is TypeScript's safe alternative to any—it accepts any value but blocks all operations until you prove what type you're working with. But how do you actually use an unknown value? You need to narrow it to something concrete.
Using typeof to Narrow unknown
The typeof operator is your primary tool for narrowing unknown values to primitive types. TypeScript's control flow analysis recognizes typeof checks and updates the type accordingly:
function processValue(input: unknown) {
if (typeof input === "string") {
// input is now string
console.log(input.toUpperCase());
}
}
Once inside the if block, TypeScript knows input must be a string, so all string methods become available.
Checking Multiple Primitive Types
You can chain typeof checks to handle different primitive types:
function describe(value: unknown): string {
if (typeof value === "number") {
return `Number: ${value.toFixed(2)}`;
}
if (typeof value === "boolean") {
return `Boolean: ${value ? "yes" : "no"}`;
}
if (typeof value === "string") {
return `String: "${value}"`;
}
return "Unknown type";
}
Each branch narrows unknown to the specific primitive that passed the check.
Why This Matters
This pattern is essential when working with external data sources, API responses, or JSON parsing—anywhere you receive untyped data but need type-safe operations.
Key Takeaway: Use typeof guards to narrow unknown values to primitives like string, number, or boolean, enabling safe access to type-specific operations while maintaining compile-time safety.