← TypeScript

Intermediate · 3 of 16 · 15 min read

Narrowing

How the compiler follows your checks to work out what a value is, which checks it understands, and the two places the narrowing is quietly lost.

  • Narrowing

A union says a value is one of several things. Narrowing is the compiler reading your runtime checks and working out which one it is in each branch — so you get the full surface of a type exactly where you have earned it.

Step through a union being narrowed by three successive checks
the value herestringnumbernulltypeof v === "string"v === nulleverything elsenarrowed tostringnullnumbernever — nothing is left

1 The parameter is string | number | null. Only what all three share is usable — which is almost nothing, so the first job is to split them up.

2 typeof v === "string" keeps one member. Inside that branch the value is a string, with every string method available.

3 v === null picks out the null. Note it has to be its own check: typeof null is "object", so a typeof test would never have caught it.

4 With the string and the null handled, the only branch left is number — the compiler worked that out by elimination, not from a check you wrote.

5 Handle that one too and nothing remains: the value is never. Assigning it to a never parameter is what turns a newly added union member into a compile error.

Each check removes members rather than converting anything. Nothing is emitted: these are ordinary runtime tests, and the narrowing is what the compiler infers from them.

The checks it understands

function describe(value: string | number | boolean | null) {
  if (typeof value === "string") return value.toUpperCase();  // string
  if (typeof value === "number") return value.toFixed(2);     // number
  if (value === null) return "nothing";                       // null
  return value ? "yes" : "no";                                // boolean
}

console.log(describe("a"), describe(1.5), describe(null), describe(true));
Check Narrows
typeof x === "string" primitives
x instanceof Cls class instances
"key" in x object union members that declare the key
x.kind === "circle" a discriminated union
if (x) removes every falsy value
x === null / x == null null, and == null also undefined
Array.isArray(x) arrays
a type predicate x is T whatever you declared

The typeof null trap

function handle(value: object | null) {
  if (typeof value === "object") {
    // value.toString(); // 'value' is possibly 'null'
  }
  if (value !== null) {
    value.toString();    // narrowed properly
  }
}

typeof null is "object" in JavaScript, and TypeScript models it faithfully. Check for null explicitly, or use a truthiness guard that removes it along with everything else falsy.

Truthiness removes more than you may mean

function count(n: number | undefined) {
  if (n) return n.toFixed(0);      // skips 0 as well
  return "none";
}

function countBetter(n: number | undefined) {
  if (n !== undefined) return n.toFixed(0);  // keeps 0
  return "none";
}

console.log(count(0), countBetter(0)); // "none" "0"

Exactly the JavaScript falsy problem, and the type system does not save you from it. if (x) is right when every falsy value means “missing”, and wrong whenever 0 or "" is real data.

in and instanceof

type Fish = { swim: () => void };
type Bird = { fly: () => void };

function move(animal: Fish | Bird) {
  if ("swim" in animal) animal.swim();   // Fish
  else animal.fly();                      // Bird
}

class Dog { bark() { return "woof"; } }
class Cat { meow() { return "meow"; } }

function speak(pet: Dog | Cat) {
  return pet instanceof Dog ? pet.bark() : pet.meow();
}

move({ swim: () => console.log("swimming") });
console.log(speak(new Dog()));

in is the natural guard for a union with no shared discriminant. instanceof works on classes — and only on classes, because it needs a constructor to check against.

Discriminated unions

The cleanest form: one shared property with a distinct literal type per member.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "square": return shape.side ** 2;
  }
}

console.log(area({ kind: "square", side: 3 })); // 9

One comparison narrows the whole object, and when every member is handled the remaining type is never — which is how you make adding a member break the build:

function assertNever(value: never): never {
  throw new Error(`unhandled: ${JSON.stringify(value)}`);
}

function areaChecked(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return 1;
    case "square": return 2;
    default: return assertNever(shape); // a third kind errors HERE
  }
}
console.log(areaChecked({ kind: "circle" } as Shape));

Where narrowing is lost

A let closed over. The compiler cannot know whether something reassigned it before the callback ran:

function withLet(input: string | undefined) {
  let value = input;
  if (!value) return;

  setTimeout(() => {
    // value.toUpperCase(); // 'value' is possibly 'undefined'
    console.log(value?.toUpperCase());
  }, 0);
}

function withConst(input: string | undefined) {
  if (!input) return;
  const value = input;                                   // cannot be reassigned
  setTimeout(() => console.log(value.toUpperCase()), 0); // narrowing holds
}
withConst("ok");

Parameters and consts keep their narrowed type inside a closure. A let does not.

Building a new value from a narrowed one. Narrowing applies to the binding, not to anything derived from it:

type State = { ok: true; data: string } | { ok: false; error: string };

function render(states: State[]) {
  // Narrow inside the callback, where the value actually is:
  return states.map((s) => (s.ok ? s.data : s.error)).join("");
}

console.log(render([{ ok: true, data: "a" }, { ok: false, error: "b" }])); // "ab"

A filter with a type predicate narrows the array itself, which is the tidier version:

type State = { ok: true; data: string } | { ok: false; error: string };

const isOk = (s: State): s is Extract<State, { ok: true }> => s.ok;

function onlyData(states: State[]) {
  return states.filter(isOk).map((s) => s.data); // string[]
}
console.log(onlyData([{ ok: true, data: "x" }]));

One deliberate unsoundness

Property narrowing survives a function call, even though the call could in principle mutate the object:

const user: { name?: string } = { name: "Ana" };

function sneaky() { delete user.name; }

if (user.name) {
  sneaky();
  // console.log(user.name.toUpperCase()); // compiles; throws at runtime
}
console.log(user.name);

Tracking that properly would make narrowing useless in real code, so the compiler trades the soundness for usability. Copy to a local when the gap matters.

Common mistakes

Using truthiness where 0 or "" is valid

Mistake. if (count) on a number | undefined. Why it fails. Zero is falsy, so a real zero takes the “missing” branch. What to do instead. !== undefined, or != null when either counts as absent.

Expecting typeof to exclude null

Mistake. typeof value === "object" to mean “a real object”. Why it fails. typeof null is "object", so null survives the check. What to do instead. typeof value === "object" && value !== null.

Narrowing a let and using it later

Mistake. Checking a let and then reading it inside a callback or after an await. Why it fails. The compiler cannot prove it was not reassigned in between, so it widens back. What to do instead. Copy the narrowed value into a const, or narrow at the point of use.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

A typeof check narrows, but the set of strings it can return has a famous gap.

Why can value still be null inside this branch?

Code sample
function handle(value: object | null) {
  if (typeof value === "object") {
    value.toString();
  }
}

What does the in operator narrow?

Narrowing is tracked per binding, and the compiler gives it up where it cannot see what happens next.

Why is value back to string | undefined inside the callback?

Code sample
function run(value: string | undefined) {
  if (!value) return;

  setTimeout(() => {
    console.log(value.toUpperCase());
  }, 0);
}

A truthiness check removes every falsy value, which is more than you sometimes mean.

Which values survive this guard?

Code sample
function handle(count: number | undefined) {
  if (count) {
    console.log(count.toFixed(0));
  }
}
Practise Narrowing →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.