Course contentsShow
← TypeScript
Lesson 191 of 1,7965. Type Narrowing FundamentalsFree lesson

Using typeof to Guard Primitives

How TypeScript narrows string | number unions when you check typeof x === 'string'.

Using typeof to Guard Primitives

What you'll learn: How TypeScript automatically narrows string | number unions when you check typeof x === 'string'.

In the previous lesson, you learned that typeof is a JavaScript operator that returns a string describing a value's type. Now we'll see how TypeScript uses this information to narrow union types.

The Magic of Type Guards

When you have a variable that could be multiple types (like string | number), TypeScript doesn't know which one it actually is. But when you write an if statement checking typeof, TypeScript watches and adjusts what it knows:

function processValue(value: string | number) {
  if (typeof value === 'string') {
    // Inside here, TypeScript KNOWS value is a string
    console.log(value.toUpperCase());
  } else {
    // And here, it KNOWS value must be a number
    console.log(value.toFixed(2));
  }
}

Think of it like a security checkpoint: When someone shows ID proving they're a student, you know they can use student services. TypeScript does the same—when typeof proves a value is a string, TypeScript lets you use string methods.

Why This Works

TypeScript tracks your runtime checks. When you test typeof value === 'string', two things happen:

  1. Inside the if block: The type narrows to string
  2. Inside the else block: The remaining type is number

This works with all primitive typeof results: 'string', 'number', 'boolean', 'undefined', 'bigint', and 'symbol'.

The Narrowing Guarantee

The beauty is that TypeScript won't let you make mistakes. Try calling toUpperCase() on the number branch, and you'll get an error—because TypeScript has narrowed the type and knows that's impossible.

Key Takeaway: When you check typeof x === 'string' on a union type, TypeScript narrows the type to string in that branch, giving you full access to string methods safely.