Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 96 ยท Narrowing

Narrowing

Learn how TypeScript narrows union types with control-flow analysis - typeof, truthiness, equality, in, instanceof, early returns and assignments - and the traps to avoid.

A union type like string | number says a value could be one of several things. That's honest, but it's not very useful on its own: you can only call methods that exist on every member of the union. To do anything specific, you first have to find out which member you're holding. TypeScript watches the checks you write (typeof x === 'string', if (user), 'id' in obj) and, inside each branch, treats the value as the more specific type. This is called narrowing.

Narrowing is not a special syntax. It's TypeScript reading ordinary JavaScript the way a careful human would. The compiler follows every if, else, return, throw, switch and assignment in your function, a process called control-flow analysis, and keeps track of what each variable can be at each point. Once you learn which checks it understands, you can write normal-looking code and get precise types for free.

This lesson covers every built-in narrowing technique. The next two lessons build on it: Discriminated Unions show the most powerful pattern for modelling data, and Custom Type Guards teach you to write your own checks.

Declared type vs narrowed type

Every variable has a declared type, the one you annotated or TypeScript inferred. At any point in the code it also has a narrowed type: the declared type minus everything the code has ruled out so far. Hover a variable in an editor and you see the narrowed type for that exact spot.

TypeScript The type changes from line to line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice the second half of the function. There's no else, yet value.toFixed(2) compiles. Because the string branch ends with return, TypeScript knows that any code after the if can only be reached when value is not a string. Early returns are the most common way to narrow, and they keep code flat.

Without the check, the same call fails: value.toUpperCase() on string | number is error TS2339, because number has no toUpperCase property.

TypeScript Using a union without narrowing (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error says Property 'toUpperCase' does not exist on type 'string | number'. and then adds the detail line Property 'toUpperCase' does not exist on type 'number'. TypeScript tells you exactly which member of the union is the problem, which is a strong hint about what to check.

typeof narrowing

The JavaScript typeof operator returns one of eight strings: 'string', 'number', 'bigint', 'boolean', 'symbol', 'undefined', 'object' and 'function'. TypeScript understands comparisons against each of them (with ===, !==, ==, != and in switch statements) and narrows accordingly.

TypeScript typeof in a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The function has no final return, yet it compiles. TypeScript sees that the five cases cover every member of Primitive, so the end of the switch is unreachable. If you later add symbol to Primitive, you get error TS2366 ("Function lacks ending return statement and return type does not include 'undefined'.") until you handle the new case. That's exhaustiveness checking, which you'll use heavily in Discriminated Unions.

typeof null is 'object'. This is a famous JavaScript mistake from 1995 that can never be fixed. TypeScript models it faithfully: if x is string[] | null, then inside if (typeof x === 'object') the type is still string[] | null. Check for null separately.

Truthiness narrowing

In JavaScript, if (x) runs its branch when x is truthy. The falsy values are false, 0, -0, 0n, NaN, '' (the empty string), null and undefined; everything else is truthy. TypeScript uses this to remove null and undefined from a type inside a truthy branch. The &&, || and ! operators narrow the same way.

TypeScript Truthiness removes null and undefined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In user.nickname && user.nickname.trim(), the right side only runs if the left side is truthy, so TypeScript knows user.nickname is a string there. The last call is interesting: the nickname is three spaces, which is truthy, but trim() turns it into '', and display || user.name then falls back to the name.

Truthiness checks have one big trap: they also reject valid falsy values. If a count can legitimately be 0 or a label can be '', if (count) treats them like "missing".

TypeScript The zero trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Both versions compile, because TypeScript can't know which one you meant. Use a truthiness check when "empty" and "missing" really mean the same thing; otherwise compare against undefined or null explicitly, or use the nullish operators ?? and ?., which only react to null and undefined (see nullish coalescing and optional chaining).

Equality narrowing

Comparing with === or !== narrows both sides. Compare against a literal and the variable becomes that literal type; compare two variables and TypeScript narrows each one to the types they have in common.

The loose comparison x != null deserves a special mention. Because null == undefined is true in JavaScript, x != null rules out both null and undefined in one check, and TypeScript knows it. It's the one place where many style guides allow ==/!=.

TypeScript Equality checks narrow both sides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In compare, a can be string | number and b can be string | boolean. If they are strictly equal, they must be the same type, and the only type in both unions is string. So inside the branch, both are narrowed to string. In isVertical, the assignment const horizontal: 'left' | 'right' = d; proves the narrowing: it would be a type error if d could still be 'up' or 'down'.

The in operator

When the members of a union are object types with different properties, use the in operator. 'swim' in animal is true when the object (or its prototype chain) has a property with that name, and TypeScript narrows to the union members that declare it.

TypeScript Narrowing objects with in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The second function shows a newer trick (since TypeScript 4.9). When data is a plain object that doesn't declare version at all, 'version' in data narrows it to object & Record<'version', unknown>. The property now exists with type unknown, and a second typeof check narrows it to string. This is the building block for validating parsed JSON, which Custom Type Guards develops fully.

in checks that a property exists, not that its value is defined. { swim: undefined } passes 'swim' in x. If an optional property is involved, check its value as well.

instanceof narrowing

For values created by classes or built-in constructors (Date, Map, Error, RegExp, your own classes), use instanceof. x instanceof Date checks the prototype chain at runtime, and TypeScript narrows x to Date in the true branch.

TypeScript instanceof with built-ins and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Order matters with instanceof: RangeError is a subclass of Error, so test the more specific class first. The explain function takes unknown, which is exactly what a catch clause gives you in strict mode. Error Handling covers that in depth.

instanceof only works with things that exist at runtime. An interface or type alias is erased when the code is compiled, so x instanceof User where User is an interface is error TS2693 ("'User' only refers to a type, but is being used as a value here."). For interfaces, use in, a discriminant property or a custom type guard.

Arrays and other built-in checks

Some library functions are declared as type guards, so calling them narrows too. The most useful is Array.isArray(x), which narrows to the array member of a union. Number.isInteger(x) does not narrow: it is declared to return a plain boolean, so an unknown value stays unknown after it.

TypeScript
function total(input: number | number[]): number {
  if (Array.isArray(input)) {
    return input.reduce((sum, n) => sum + n, 0); // input: number[]
  }
  return input; // input: number
}

Assignments narrow too

When you assign to a variable whose declared type is a union, TypeScript narrows it to the type of the value you assigned. Later you may assign any other member of the declared type, but never something outside it.

TypeScript Assignment narrowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The // @ts-expect-error comment tells the compiler "the next line has a type error, and that's intended". The program still compiles, and if the line ever stops being an error, TypeScript reports the unused directive. It's a handy way to show an error inside an otherwise runnable example, but in real code fix the error instead. Note that at runtime the assignment still happens, so the last line prints true.

Where narrowing stops

Narrowing is tied to control flow, so a few situations reset it:

  • Callbacks that run later. Narrowing of a let variable is not trusted inside a function created before the variable is reassigned, because the callback could run after the change. Since TypeScript 5.4, narrowing is kept inside closures created after the last assignment, which covers most real code. Copying the narrowed value into a const always works.
  • Properties after a function call. TypeScript keeps a narrowed property like obj.value after unrelated function calls, even though the call could have changed it. This is a deliberate trade-off for convenience; just be aware it isn't a guarantee.
  • Separate checks stored in variables. Since TypeScript 4.4, const isText = typeof x === 'string'; if (isText) { ... } narrows x, as long as both the check result and x are const (or parameters that are never reassigned).
TypeScript Aliased conditions and closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The ?? '(none)' is there because indexing an array can go past its end. Our editor doesn't enable noUncheckedIndexedAccess, so names[i] is typed string; with that flag it would be string | undefined, which is the more honest type (see Strict Mode Explained).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside if (typeof x === 'object'), where x: string[] | null, what is the type of x?

    typeof null is 'object' in JavaScript, so the check keeps both members. You still need x !== null to get string[].
  2. 2. Which check removes both null and undefined from string | null | undefined without rejecting the empty string?

    Loose != null is false for both null and undefined, and TypeScript narrows accordingly. if (text) would also reject '', and !== null keeps undefined.
  3. 3. interface Cat { meow(): void } and interface Dog { bark(): void }. Which check narrows pet: Cat | Dog to Cat?

    Interfaces don't exist at runtime, so instanceof Cat is error TS2693, and typeof never returns 'Cat'. Reading pet.meow directly is an error because Dog has no meow. The in operator is the right tool.
  4. 4. let v: string | number = 'a'; v = 5; What is the type of v on the next line?

    Assignment narrows a variable to the assigned value's type, widened for a let to number. The declared type string | number still decides what you may assign later.
  5. 5. A function returns early when typeof value === 'string'. What type does value: string | boolean have after that if?

    Control-flow analysis knows the string case already returned, so only boolean can reach the code after the if.

Summary

  • Narrowing is TypeScript refining a union type inside a branch, based on the ordinary checks you write. It follows if, else, return, throw, switch, &&, || and assignments (control-flow analysis).
  • typeof narrows primitives and functions; remember that typeof null === 'object'.
  • Truthiness checks remove null and undefined, but also reject 0, '' and NaN. Compare explicitly when those are valid values.
  • ===/!== narrow both sides; x != null removes null and undefined together.
  • 'prop' in obj narrows object unions and can add an unknown property to a plain object.
  • instanceof narrows class instances and built-ins; it can't be used with interfaces or type aliases.
  • Assignments narrow a variable to the assigned type, within its declared type. Narrowing survives const aliases and closures created after the last assignment.

Next: Discriminated Unions