TypeScript Developer interview question · Most asked

What is type narrowing and what techniques does TypeScript support?

Summary

Narrowing refines a broad type to a more specific one within a code branch, based on control-flow analysis of checks like typeof, instanceof, in, equality, truthiness, discriminant properties, and user-defined type guards (x is T) or assertion functions (asserts x is T).

Longer Answer

The compiler tracks types through if/switch/early returns. Since TypeScript 5.5, the compiler can infer type predicates from simple functions like x => x !== null, so array.filter(...) narrows correctly. Assertion functions throw if the condition fails and narrow afterwards.

Code Example

type Shape = { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number };

function area(s: Shape): number {
  switch (s.kind) {
    case "circle": return Math.PI * s.r ** 2;   // s narrowed to circle
    case "rect":   return s.w * s.h;
  }
}

function isString(x: unknown): x is string {
  return typeof x === "string";
}

const ids = [1, null, 3].filter((x) => x !== null); // number[] (TS 5.5+)

Key Points

  • typeof, instanceof, in, equality
  • Discriminated unions with switch
  • Custom guards: (x): x is T
  • Assertion functions: asserts x is T
  • TS 5.5 infers type predicates

More most-asked TypeScript Developer questions

← All TypeScript Developer questions