Type Guards & Narrowing

Difficulty: Intermediate

Question

What are type guards in TypeScript, and how does the compiler narrow a union type based on runtime checks like `typeof`, `instanceof` and `in`?

Answer

A type guard is a runtime check that TypeScript understands well enough to narrow a variable's type inside the guarded block. After if (typeof id === "string"), the compiler treats id as string in that branch and as the remaining union members in the else. This process is called control flow narrowing, and it is how you work safely with unions without casting.

The built-in guards

How control flow analysis works

The compiler tracks every assignment and condition along each code path. Early returns narrow everything after them, switch cases narrow per branch, and && and || narrow their right-hand sides. Narrowing resets when a variable is reassigned, and it does not survive into callbacks for let variables because the callback could run later after reassignment. Using const or copying to a local fixes that.

Custom type guards (type predicates)

When the check is too complex for the built-ins, write a function returning value is Type. TypeScript trusts this predicate completely, so a buggy guard is as dangerous as a wrong cast. Since TypeScript 5.5 the compiler can infer simple predicates automatically, so arr.filter(x => x !== undefined) now returns T[] instead of (T | undefined)[].

Assertion functions (asserts value is Type) are the throwing variant: after calling assertIsUser(x), the rest of the scope sees x as User. They pair well with validation libraries.

Where guards show up in practice

Common mistakes

Narrowing string | number | null. Each check removes possibilities from the union along that code path.
  1. id: string | number | null: Declared union type.
  2. if (id === null) return: Early return removes null.
  3. typeof id === 'string': True branch sees string.
  4. else branch: Only number remains.

Code examples

Built-in narrowing

type Amount = number | string | null;

function toPaise(amount: Amount): number {
  if (amount === null) return 0;        // null removed below
  if (typeof amount === "string") {
    return Math.round(parseFloat(amount) * 100); // amount: string
  }
  return Math.round(amount * 100);      // amount: number
}

class ApiError extends Error { constructor(public status: number) { super(); } }

function handle(err: unknown) {
  if (err instanceof ApiError) return err.status; // ApiError
  if (err instanceof Error) return err.message;   // Error
  return String(err);                              // unknown
}

Equality, typeof and instanceof checks each narrow the union along their branch. In catch blocks errors are unknown by default under strict, so instanceof is the standard narrowing tool.

in operator and custom predicates

interface CardPayment { cardLast4: string }
interface UpiPayment { vpa: string }
type Payment = CardPayment | UpiPayment;

function describe(p: Payment) {
  if ("vpa" in p) return `UPI ${p.vpa}`;   // UpiPayment
  return `Card ending ${p.cardLast4}`;      // CardPayment
}

// Custom type guard with a type predicate
function isUpi(p: Payment): p is UpiPayment {
  return typeof (p as UpiPayment).vpa === "string";
}

const payments: Payment[] = [{ vpa: "asha@okaxis" }, { cardLast4: "4242" }];
const upiOnly = payments.filter(isUpi); // UpiPayment[]

The in operator narrows object unions by property presence. A predicate function lets you reuse a check, and filter uses it to narrow the array type.

Assertion functions and inferred predicates (TS 5.5+)

function assertIsString(v: unknown, name: string): asserts v is string {
  if (typeof v !== "string") throw new TypeError(`${name} must be a string`);
}

function readEnv(key: string): string {
  const value = process.env[key]; // string | undefined
  assertIsString(value, key);
  return value;                   // string from here on
}

// TypeScript 5.5+ infers the predicate for simple arrow functions
const ids = ["a", undefined, "b"].filter((x) => x !== undefined);
//    ^? string[]  (was (string | undefined)[] before 5.5)

An asserts signature narrows everything after the call or throws. From TypeScript 5.5 the compiler infers type predicates for simple filter callbacks.

Key points

Common follow-up questions

Interview tips

Concepts covered

Type Guards, Control Flow Narrowing, Type Predicates, instanceof, in Operator, Assertion Functions

More TypeScript Interview questions