Skip to the content

Lesson 106 of 296

Narrowing

What you will learn

  • What narrowing is
  • typeof, truthiness and equality narrowing
  • The in operator
  • instanceof and Array.isArray
  • Control flow analysis
On this page

What is narrowing?

When a value has a wide type, such as string | number | null, TypeScript only allows what is safe for all possibilities. Narrowing means using normal JavaScript checks so TypeScript can work out a more specific type inside a block.

TypeScript follows your if, return, switch and throw statements to know the type at each line. This is called control flow analysis.

typeof

function format(value: string | number) {
  if (typeof value === "string") {
    return value.trim();          value: string
  }
  return value.toFixed(2);        value: number
}

typeof narrows to "string", "number", "boolean", "bigint", "symbol", "undefined", "function" and "object". Remember typeof null === "object" (Lesson 30), so for objects also check for null.

Truthiness

function greet(name: string | null | undefined) {
  if (name) {
    return `Hello ${name}`;       name: string
  }
  return "Hello guest";
}

Careful: truthiness also removes "" and 0 (Lesson 46). For numbers, check for null explicitly.

Equality

function check(a: string | number, b: string | boolean) {
  if (a === b) {
    a.toUpperCase();      both must be string here
  }
}

function show(value: string | null) {
  if (value !== null) {
    value.length;         value: string
  }
}

value != null (loose) removes both null and undefined.

The in operator

Checks whether a property exists, and narrows object unions:

type Card = { cardNumber: string };
type PayPal = { email: string };

function describe(payment: Card | PayPal) {
  if ("cardNumber" in payment) {
    return `Card ending ${payment.cardNumber.slice(-4)}`;
  }
  return `PayPal: ${payment.email}`;
}

instanceof

For classes, including built-in ones like Date and Error:

function toTimestamp(value: Date | string) {
  if (value instanceof Date) {
    return value.getTime();
  }
  return Date.parse(value);
}

Array.isArray

function toList(input: string | string[]) {
  return Array.isArray(input) ? input : [input];
}

Narrowing with early returns

function getEmail(user: User | undefined): string {
  if (!user) {
    throw new Error("No user");
  }
  return user.email ?? "no email";     user: User from here on
}

After the throw, TypeScript knows user cannot be undefined anymore.

Narrowing and assignments

let value: string | number = "hello";
value.toUpperCase();     fine: TypeScript knows it is currently a string
value = 42;
value.toFixed();         fine: now a number

When narrowing is lost

Narrowing does not survive into callbacks if the variable can change later:

let user: User | undefined = getUser();
if (user) {
  setTimeout(() => {
    user.name;         may be an error: user could have changed by then
  });
}

Fix: copy it into a const first.

Common mistakes

  • Using typeof x === "object" without excluding null.
  • Truthiness narrowing on numbers where 0 is valid.
  • Writing as (Lesson 113) to force a type instead of narrowing properly.

How to say it in an interview

"Narrowing uses ordinary runtime checks, typeof, truthiness, equality, the in operator, instanceof and Array.isArray, and TypeScript's control flow analysis then knows the more specific type inside each branch. Early returns and throws narrow the rest of the function. I prefer narrowing to type assertions because the check really happens at runtime."

Key words

WordMeaning
NarrowingRefining a wide type to a more specific one
Control flow analysisTypeScript following your code to track types
Type guardA check that narrows a type
in operatorChecks whether a property exists

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.