सामग्री पर जाएँ

TypeScript Reference · Concepts and Comparisons

Widening and narrowing in TypeScript

Understand how literal types widen to string or number, how control flow narrows unions, and how to keep or reset a type with const and guards.

A type in TypeScript is not fixed at the declaration. It moves in two directions. Widening makes it more general: the literal "red" becomes string. Narrowing makes it more specific: a string | number becomes string after a typeof check.

Knowing which way a type moves, and when, explains most "why is this string and not "red"?" surprises.

TypeScript
let a = "red";        // widened to string
const b = "red";      // stays the literal "red"

Try it

TypeScript Widening from literals

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Narrowing a union

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Widening

  • let and var widen a literal initializer to its primitive type, because the variable can change.
  • const keeps the literal type for primitives.
  • Object and array literals widen their properties and elements, even under const, since the contents are mutable.
  • Function return types widen literal returns unless the context expects a literal type.
  • as const or a type annotation stops widening and makes properties readonly with literal types.
  • null and undefined widen to any only without strictNullChecks; with it, they stay distinct.

Narrowing

Narrowing follows control flow. These constructs refine a type inside a branch:

  • typeof, instanceof, in checks
  • Equality (===, !==) and truthiness tests
  • Discriminant property checks on tagged unions
  • User-defined type guards (x is T) and assertion functions
  • Array.isArray and similar built-in guards

Usage notes

  • Narrowing is lost across function boundaries. A callback may run after a variable changed, so a narrowed let is widened again inside closures (except for const and parameters never reassigned).
  • Assignments narrow too, as the second example shows: the declared type stays the limit, the assigned value picks the current type.
  • Exhaustive checks assign the leftover value to never to prove all cases are handled; see Exhaustive checks.
  • Widening is the reason Object.keys(obj) gives string[], not a union of keys.
  • Do not fight narrowing with as. An assertion hides bugs that a guard would catch.