Course contentsShow
← TypeScript
Lesson 1701 of 1,79639. TypeScript PerformanceFree lesson

Widening: From Literal to General Types

How TypeScript automatically widens literal types during inference to maintain flexibility.

Widening: From Literal to General Types

What you'll learn: How TypeScript automatically converts specific literal types into broader primitive types during type inference to maintain flexibility.


What Is Widening?

When you declare a variable with let or var, TypeScript doesn't just remember the exact literal value you assigned—it widens the type to a more general primitive type. This automatic broadening happens during inference to give you flexibility to reassign that variable later.

Think of widening like buying a container: if you purchase a water bottle, you're not committed to only drinking that exact same water forever. The bottle can hold other compatible liquids. Similarly, when TypeScript sees let x = 5, it infers x: number (not x: 5), allowing you to later assign x = 10.


How Widening Works

When TypeScript infers the type of a mutable variable, it widens literal types to their corresponding primitive types:

  • String literals ("hello") → string
  • Numeric literals (42) → number
  • Boolean literals (true) → boolean

This widening only happens with mutable declarations (let and var). Constants (const) don't widen because they can't be reassigned—TypeScript keeps the precise literal type.


Why Widening Exists

Without widening, every let variable would be stuck with its initial value's type forever. You'd get errors trying to reassign perfectly valid values:

let count = 0;  // If TypeScript inferred type `0`, this would be useless
count = 1;      // Error without widening!
count = 2;      // Error without widening!

Widening makes mutable variables practical while still providing type safety at the primitive level.


The const vs let Difference

This is where widening becomes visible:

  • const x = "hello" → Type inferred as "hello" (literal type, no widening)
  • let x = "hello" → Type inferred as string (widened from literal)

The mutability of the binding determines whether widening occurs.


When Widening Can Surprise You

Sometimes you want a literal type even with let. In those rare cases, you need an explicit type annotation or as const to prevent widening. But by default, TypeScript assumes flexibility is what you need.


Key Takeaway: TypeScript automatically widens literal types to primitives for let/var declarations, trading precision for flexibility—this is essential for practical variable reassignment while maintaining type safety.