Skip to the page

How TypeScript thinks · core

Narrowing and type guards

Narrowing is how TypeScript follows your runtime checks (typeof, instanceof, in, equality, truthiness, custom guards) to a more specific type inside each branch.

The notes

What you must know

  • Built-in guards: typeof x === 'string', x instanceof Date, 'key' in obj, x === null, Array.isArray(x), truthiness.
  • A user-defined guard returns value is T: function isUser(x: unknown): x is User. TypeScript trusts it, so it must be correct.
  • Assertion functions asserts x is T narrow everything after the call; they must throw when the check fails.
  • Since TS 5.5, a function like x => x !== null is inferred as a type predicate, so arr.filter(x => x !== null) gives a non-null array.
  • Narrowing is lost across callbacks for let variables that may be reassigned; copy to a const first.

The red pen

Common traps: mistake → fix

  • Mistake: "a type guard checks the type for you"

    Fix: it only checks what your code checks; a wrong guard lies to the compiler.

  • Mistake: "typeof null is 'null'"

    Fix: it is 'object', so typeof x === 'object' does not exclude null.

Easy to hard

Questions interviewers ask, easy to hard

  1. What ways do you know to narrow a union?
  2. What is a user-defined type guard and what is the risk?
  3. Why does .filter(Boolean) not always narrow, and what changed in TS 5.5?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview