Course contentsShow
← TypeScript
Lesson 132 of 1,7963. Basic TypesFree lesson

Narrowing unknown with typeof

Use typeof guards to safely narrow unknown to primitive types before use.

What You'll Learn

You'll learn how to unlock the value inside an unknown variable by using typeof guards to safely narrow it down to a specific primitive type.


The Core Idea

You've learned that unknown forces you to check what's inside before you use it. But how do you check? The typeof operator is your first tool.

When you write a condition like typeof value === "string", TypeScript recognizes this pattern and narrows the type of value from unknown to string inside that block. This is called type narrowing — you're proving to TypeScript what the value actually is.

Think of it like a security checkpoint: the guard (typeof) verifies the identity (type) of an unknown visitor before letting them into a restricted area (your type-safe code).


Using typeof to Narrow

function processValue(value: unknown) {
  if (typeof value === "string") {
    // ✅ Inside here, value is now string
    console.log(value.toUpperCase());
  }
  
  if (typeof value === "number") {
    // ✅ Inside here, value is now number
    console.log(value.toFixed(2));
  }
  
  if (typeof value === "boolean") {
    // ✅ Inside here, value is now boolean
    console.log(value ? "yes" : "no");
  }
}

Outside the if blocks, value remains unknown. Inside each block, TypeScript knows exactly what type it is because you proved it with typeof.

You can check for: "string", "number", "boolean", "bigint", "symbol", "undefined", "object", or "function".


Why This Matters

Without narrowing, unknown is useless — you can't call methods or access properties. The typeof guard transforms unknown into something actionable while keeping you safe from runtime crashes.

Key Takeaway: Use typeof guards to narrow unknown to primitive types, unlocking type-safe access to the value inside.