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

Control Flow Analysis After typeof

Understanding how TypeScript tracks narrowed types through if/else branches and beyond.

Control Flow Analysis After typeof

You'll learn: How TypeScript remembers narrowed types as your code branches through if/else blocks and beyond.

The Smart TypeScript Compiler

When you use a typeof check to narrow a type, TypeScript doesn't just recognize it at that exact line—it tracks what you've learned through the rest of your code's control flow. This is called control flow analysis.

Think of TypeScript as having a memory: once you've checked typeof value === 'string', TypeScript remembers "inside this if-block, value is definitely a string" and gives you all string methods and properties.

How It Works

After a typeof guard, TypeScript follows your code's logical path:

function process(value: string | number) {
  if (typeof value === 'string') {
    // TypeScript knows: value is string here
    value.toUpperCase(); // ✓ string methods available
  } else {
    // TypeScript knows: value must be number here
    value.toFixed(2); // ✓ number methods available
  }
  
  // Outside the branches: value is string | number again
}

Notice how TypeScript automatically figures out that if value isn't a string in the else-branch, it must be a number. You didn't need another typeof check!

The Magic of Elimination

TypeScript uses process of elimination: if you check one type from a union, the other branch gets the remaining types automatically. The compiler tracks these narrowed types through your entire function's flow.

Key Takeaway: TypeScript's control flow analysis tracks narrowed types through if/else branches, remembering what you've proven about a value's type in each code path—no repeated checks needed.