Type Narrowing

How TypeScript works out which branch of a union you're holding at each point in the code.

What is it?

With a union like string | number, TypeScript won't let you treat the value as one or the other. .toUpperCase() is rejected, because the value might be a number.

But once you write a check like typeof value === "string", TypeScript notices. Inside the block where the check passed, value is a string, and string methods work with no cast or annotation. This is called type narrowing.

TypeScript recognizes these common checks:

  • typeof, for primitives like string, number and boolean.
  • instanceof, for instances of a class.
  • Truthy/falsy checks, like if (value).
  • Checking a property that only exists on one branch of the union.

Explain like I'm 10

It's like sorting mail. You don't know what's inside until you look at the envelope, but once you see it's the electric bill, you know exactly what's in it and can act without guessing.

Examples

Narrowing with typeof

function printLength(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase()); // value is narrowed to string here
  } else {
    console.log(value.toFixed(2));    // value is narrowed to number here
  }
}

Inside the if, value is a string, the only way the typeof check could pass. In the else, it's number, the only possibility left.

Narrowing with instanceof and property checks

class Dog {
  bark() { console.log("Woof!"); }
}

class Cat {
  meow() { console.log("Meow!"); }
}

function speak(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark(); // narrowed to Dog
  } else {
    animal.meow(); // narrowed to Cat
  }
}

interface Success {
  ok: true;
  data: string;
}
interface Failure {
  ok: false;
  error: string;
}

function handle(result: Success | Failure) {
  if (result.ok) {
    console.log(result.data);  // narrowed to Success
  } else {
    console.log(result.error); // narrowed to Failure
  }
}

instanceof narrows between classes. Checking a shared property with a distinct literal value (ok: true vs. ok: false) narrows between interfaces. This pattern is called a discriminated union.

How it works

At every point in your code, the compiler tracks the narrowest type it can prove a variable has. This is control flow analysis.

When it sees a recognized check (typeof, instanceof, a truthy check, comparing a shared "tag" property to a value, and a few others), it narrows the type inside the branch where the check is true, and narrows it differently, or not at all, outside it. This is pure code analysis; no runtime type information is added beyond the check you wrote.

Why does it exist?

Unions are only useful if you can narrow them to act on a specific branch. Narrowing rewards the runtime checks you'd write anyway (an if, a typeof) with more precise types, so you don't write anything extra just for the type checker.

When to use it

When you need to do something specific to one branch of a union, write the check first (typeof, instanceof, a property check), then use the branch-specific feature. Discriminated unions (interfaces sharing one "tag" property with distinct literal values) are a clean, common way to model success/failure or variant states.

When not to use it

You don't opt in or out of narrowing; it happens whenever you write a recognized check. What to avoid is a manual cast (as SomeType) instead of a real runtime check. A cast tells the compiler to trust you without verifying anything at runtime.

Common mistakes

  • Using a cast (as string) to silence an error instead of a real runtime check. It gives no safety and can be wrong.

  • Expecting narrowing to survive a function call between the check and the use. TypeScript can lose a narrowed type there, since the function could in theory change the value.

  • Forgetting instanceof only narrows between classes, not interface shapes. Those need a discriminant property check.

Practice exercises

  1. Easy:

    Using typeof narrowing, write formatValue(value: string | boolean) that uppercases a string, or returns "YES"/"NO" for a boolean.

  2. Medium:

    Define interfaces Circle { kind: "circle", radius: number } and Square { kind: "square", side: number }. Write area(shape: Circle | Square): number using a discriminated union check on kind.

  3. Hard:

    Write a function that accepts unknown and narrows it step by step (it's an object, then it has a specific property of the right type) before using it, with no as casts.

Interview questions

What is type narrowing?

TypeScript refining a value's type to something more specific inside a branch, based on a runtime check like typeof, instanceof or a property comparison.

Why does TypeScript disallow calling `.toUpperCase()` on a value typed `string | number` before any check?

The value could be a number, which has no .toUpperCase(), so the call isn't valid for every case. Narrowing first proves which branch you have.

Inside `if (typeof value === "string") { ... } else { ... }` for a `value: string | number`, what is `value`'s type in each branch?

string in the if, the only way the check could pass. number in the else, the only branch left.

What can `instanceof` narrow between, and what can't it narrow between?

It narrows between classes. It can't narrow between interface shapes, because interfaces have no runtime class to check against.

What is a discriminated union, and what property makes narrowing on it reliable?

A union of object types that share one property (the discriminant) with a distinct literal value per type. Checking that property narrows to the matching branch.

Given `Success { ok: true; ... }` and `Failure { ok: false; ... }`, why does `if (result.ok)` narrow `result` to `Success`?

Only Success has ok typed as literal true, so a truthy ok means result must be a Success.

What is control flow analysis, and how does it relate to narrowing?

The compiler tracking the narrowest type it can prove a variable has at every point in the code. Narrowing is the visible result when it recognizes a check like typeof or instanceof.

How does a plain truthy check like `if (value)` act as a narrowing mechanism?

It removes falsy values (null, undefined, 0, "", NaN, false) inside the if, so string | null narrows to string.

Why is a type cast like `value as string` considered less safe than proper narrowing?

A cast makes the compiler trust your claim without checking. Narrowing is based on a real runtime check the compiler can see.

Why can narrowing be "lost" if you call another function between the check and the use of the narrowed value?

TypeScript can't be sure the call didn't change the value (for example through a shared mutable variable), so it falls back to the wider original type.

How would you safely narrow a value typed `unknown` down to a specific shape without using `as` casts?

Step by step. First confirm it's a non-null object with typeof value === "object" && value !== null, then check the property you need with in or a typeof check on it, narrowing further each time.

When would you reach for `typeof` versus `instanceof` to narrow a union?

typeof for primitives like string, number and boolean. instanceof for instances of different classes.

Why doesn't `instanceof` work to narrow between two plain interfaces with no classes involved?

instanceof checks against a runtime constructor, and interfaces don't exist at runtime. Use a distinguishing property instead, as in a discriminated union.

What's the classic trap with using `typeof value === "object"` to narrow a union that might include `null`?

typeof null is "object" in JavaScript, so the check doesn't rule out null. Add an explicit value !== null.

How does checking for a property with the `in` operator (e.g. `"bark" in animal`) act as a narrowing check?

If only one branch of the union declares that property, a passing in check proves the value is from that branch.

Given `function handle(x: string[] | undefined) { if (x) { ... } }`, what's `x`'s narrowed type inside the `if`, and what does that check *not* guarantee?

string[], since the truthy check rules out undefined. It doesn't guarantee the array is non-empty; an empty array is still truthy.

Why is control flow analysis purely a compile-time, static process, adding no runtime type information beyond what you actually wrote?

The compiler only reasons about which checks appear in the code and where. It adds no runtime checks or metadata; narrowing just interprets your existing checks more precisely.

What breaks if two branches of an intended discriminated union accidentally use the same literal value for their shared tag property?

A check for that value no longer tells you which branch you have, so narrowing on the tag stops working.

If a narrowed variable is reassigned to a wider value inside the same branch, does the narrowed type persist for the rest of that branch?

No. Control flow analysis re-evaluates the type after every assignment, so a wider value widens the type again from that point on.

How does a truthy check like `if (value)` differ in behavior from an explicit `if (value !== undefined)` when narrowing `string | undefined`?

A truthy check also excludes the empty string "", even though it's a valid string. !== undefined only rules out undefined, so "" stays in the string branch.

Why doesn't calling an arbitrary custom function like `isString(value)` automatically narrow a union the way `typeof value === "string"` does?

TypeScript only recognizes a fixed set of built-in check patterns. A plain function's return type doesn't tell the compiler which branch was proven, unless the function is declared as a type guard.

What is a user-defined type guard, and how does it let a custom function participate in narrowing?

A function whose return type is a type predicate, like value is string. A truthy return tells the compiler the argument is a string, so the custom check narrows just like typeof.

For `animal: Dog | Cat`, why does `else` alone (after `if (animal instanceof Dog)`) safely narrow to `Cat` without a second `instanceof` check?

Once Dog is ruled out, Cat is the only possibility left, so the else narrows to it by elimination.

Can narrowing be lost inside a closure or callback defined within an already-narrowed branch, such as inside a `setTimeout` callback?

Yes. TypeScript can't be sure the outer variable wasn't reassigned before the callback runs, so it widens the type back inside the callback.

When is a discriminated union preferable to an `instanceof` check for distinguishing variants?

For plain data shapes (interfaces) with no classes, which are also easy to serialize. instanceof fits when the variants are real classes with their own methods.

What guarantee do you lose by using an `as` cast instead of a genuine narrowing check?

The check that the value really is what you claim. A wrong cast compiles cleanly but can fail at runtime, where a real check would have caught it.

Given `function printLength(value: string | number) { if (typeof value !== "string") { value.toFixed(2); } }`, is calling `.toFixed(2)` inside the `if` valid, and why?

Yes. Negated checks narrow too: the branch only runs when value is not a string, so it must be a number.

Why is narrowing described as something you don't opt into or out of, and what does that imply about how to write runtime checks generally?

It happens automatically whenever the compiler recognizes a supported check. Writing the checks you'd write anyway (an if, a typeof) is enough; no extra annotation is needed.