QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Type narrowing and type guards

Basic narrowing: typeof, instanceof, in, truthiness

Narrowing is control flow analysis: after a type check the compiler knows a more precise type of the variable in that branch. It works for typeof, instanceof, in, comparisons and an early return. The compiler handles the type, not the meaning of the condition: if (amount) also discards zero, so for numbers use an explicit comparison. Other traps: typeof null gives object, and instanceof does not work for data parsed from JSON.

TypeScript · Narrowing

A transfer of 0 shows as "n/a" while the test for a non-zero amount is green. What did if (amount) swallow?

A formatting function takes an optional amount and checks it with if (amount). A test with 150 passes and nobody thinks about zero. Yet zero is a valid value in a financial domain, and that check discards it. This is a typical narrowing situation: the compiler helped with the type, but a human wrote the condition. The lesson covers how TypeScript narrows a type after a check, which tools exist and where they are tricky.

How it works and why. Narrowing is control flow analysis. The compiler reads if, switch, an early return and throw, and at each point of the code knows which variants of the type are still possible. For a variable of type string | number, after typeof v === 'number' the type is number in the if branch and string in the rest. It is designed so because JavaScript already uses exactly such checks: TypeScript adds no new syntax, it understands the existing one. Hence the rule: only what is visible in the code narrows. A condition computed elsewhere and stored in a variable gives no narrowing (the compiler handles simple cases, but do not rely on it for complex ones).

What narrows

typeof x === "number"primitives, but typeof null is objectx instanceof Errorclass instances, errors included"errors" in bodya field present in a union of objectsx !== undefined, x === "FAILED"exact values, the most reliable
Figure 1. The four main checks. An exact comparison is the most reliable, the others have exceptions.
type Value = string | number | null | Date | { code: string };

function show(v: Value): string {
  if (v === null) return 'null';
  if (typeof v === 'string') return v.trim();
  if (typeof v === 'number') return v.toFixed(2);
  if (v instanceof Date) return v.toISOString();
  return v.code; // only { code: string } is left
}
type Body = { data: Account } | { errors: string[] };

if ('errors' in body) {
  console.log(body.errors.join(', '));
} else {
  console.log(body.data.id);
}

typeof returns one of the strings 'string', 'number', 'boolean', 'undefined', 'object', 'function', 'bigint', 'symbol'. A trap: typeof null === 'object', so objects get a separate !== null. instanceof works with classes and checks the prototype chain, so it fails for an object created in another realm (an iframe) and for plain JSON data. in checks that a property exists and narrows a union of objects. Equality narrows a union of literals. Under strict the catch variable is unknown (the useUnknownInCatchVariables option), so the pattern below is routine:

try {
  await client.createTransfer(payload);
} catch (err) {
  // under strict err is unknown
  const msg = err instanceof Error ? err.message : String(err);
  console.error(msg);
}

Example: truthiness and zero. Back to the function from the start.

function formatAmount(amount?: number): string {
  if (amount) return amount.toFixed(2);
  return 'n/a';
}

formatAmount(0); // 'n/a', but it should be '0.00'

The if (amount) check discards not only undefined but all "falsy" values: 0, -0, 0n, an empty string, NaN, false and null. For an optional amount that is an error the compiler cannot see: the type is narrowed correctly, but the condition is wrong. A test with a non-zero amount does not show it. What is needed is a check of exactly what you mean:

function formatAmount(amount?: number): string {
  if (amount !== undefined) return amount.toFixed(2);
  return 'n/a';
}

formatAmount(0); // '0.00'

Truthiness or an explicit check

Wrong

if (amount)

Zero, an empty string and NaN fall into "no value". For amounts, counters and quantities that is data loss.

Right

amount !== undefined

Discards only what you meant. Zero remains a valid amount.

Figure 2. Truthiness fits only where zero and an empty string really mean "no value".

Limits and alternatives. Narrowing lives within the control flow. A narrowed let or parameter may become wide again inside a callback if it is assigned after the callback is created or inside another function; a const stays narrow. After a plain function call the narrowing is kept: the compiler optimistically assumes the call did not touch the variable. Newer compiler versions keep narrowing in closures better when the variable is not reassigned after the check (this appeared in TypeScript 5.4), but it is more reliable to pull the value into a const. An early exit narrows as well: after if (!account) throw new Error('not found') the variable is no longer undefined. When many checks are needed they move into a custom type guard or a schema.

Common mistakes.

  • if (value) for numbers and strings where 0 or an empty string are valid: data is silently lost.
  • typeof x === 'object' without !== null: the next field access fails on null.
  • instanceof for JSON data: these are plain objects, not class instances, so the check is always false.
  • Relying on the narrowing of a let inside a callback: the value could have changed and the type is wide again.

Check yourself

Why does if (amount) narrow number | undefined to number correctly by type, yet is still a bug for an amount formatter?

Answer

The type is narrowed correctly, but the condition also discards 0. Narrowing is about the type, not the meaning of the check, so for zero you need the comparison amount !== undefined.

In catch (err) the code err.message does not compile under strict. Why, and which check fixes it?

Answer

Anything can be thrown, so err in catch is unknown. The check err instanceof Error narrows it to Error, and then message is available.

In an interview. Junior: Narrowing is when, after a typeof, instanceof, in or comparison check, TypeScript understands a more precise type of the variable. Middle/Senior: The compiler analyses control flow, and the logic of the check stays with me: typeof null gives object, truthiness discards zero, instanceof fails for JSON and the narrowing of a let is lost in callbacks. So for numbers I use an explicit comparison and for outside data a schema check.

More articles in this chapter