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

What Is Type Narrowing?

Understanding how TypeScript refines union types into more specific types within conditional branches.

What Is Type Narrowing?

You'll learn how TypeScript automatically makes broad types more specific when you check them in your code.

The Core Idea

Imagine you have a function that accepts either a string or a number. Initially, TypeScript only knows it's one of those two — it can't let you call .toUpperCase() (string method) or .toFixed() (number method) because it doesn't know which type you actually have.

Type narrowing is TypeScript's ability to refine a union type (like string | number) into a more specific type (like just string) when you perform checks like typeof or conditionals. Inside those checks, TypeScript "narrows down" what the type could be.

Think of it like sorting mail: you start with a pile that could be bills or letters. Once you check "is it from the bank?", you've narrowed that piece down to definitely being a bill, and you can treat it accordingly.

How It Works in Practice

When you write an if statement that checks the type of a value, TypeScript follows along:

  • Before the check: TypeScript knows the value is string | number
  • Inside the if block: TypeScript knows it's just string
  • Inside the else block: TypeScript knows it must be number

TypeScript uses your runtime checks (the code that actually runs) to improve its compile-time understanding. This happens automatically — you don't need special syntax beyond the normal JavaScript checks you'd write anyway.

This is incredibly powerful because it means you get precise autocomplete and safety exactly where you need it, just by writing normal defensive code.

Key Takeaway: Type narrowing is TypeScript's ability to refine union types into more specific types based on conditional checks, giving you precise type safety exactly where your code logic proves what type you're working with.