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.
let a = "red"; // widened to string const b = "red"; // stays the literal "red"
Try it
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.
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
letandvarwiden a literal initializer to its primitive type, because the variable can change.constkeeps 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 constor a type annotation stops widening and makes propertiesreadonlywith literal types.nullandundefinedwiden toanyonly withoutstrictNullChecks; with it, they stay distinct.
Narrowing
Narrowing follows control flow. These constructs refine a type inside a branch:
typeof,instanceof,inchecks- 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
letis widened again inside closures (except forconstand 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
neverto prove all cases are handled; see Exhaustive checks. - Widening is the reason
Object.keys(obj)givesstring[], not a union of keys. - Do not fight narrowing with
as. An assertion hides bugs that a guard would catch.