Course contentsShow
← TypeScript
Lesson 146 of 1,7964. Type InferenceFree lesson

Widening: From Literal to Broader Types

Understanding when TypeScript widens specific literals to general types like string or number.

Widening: From Literal to Broader Types

You'll learn: How TypeScript automatically widens specific literal values into more general types to make your code more flexible.

What Is Widening?

When you assign a literal value to a variable using let or var, TypeScript doesn't lock the type to that exact literal. Instead, it widens the type to a broader category. For example, the literal "hello" widens to the type string, and the literal 42 widens to number.

This happens because TypeScript assumes you might reassign the variable later. If it kept the type as the exact literal "hello", you couldn't assign "goodbye" afterward!

How Widening Works

let message = "hello";  // Type inferred as string, not "hello"
message = "goodbye";    // ✓ OK: string accepts any string

let count = 42;         // Type inferred as number, not 42
count = 100;            // ✓ OK: number accepts any number

Compare this to const, which prevents reassignment and keeps the literal type:

const fixed = "hello";  // Type inferred as "hello" (literal)
// fixed = "goodbye";   // ✗ Error: can't reassign const

Why It Matters

Widening balances specificity with flexibility. TypeScript knows that mutable variables (let/var) will likely hold different values over time, so it gives you room to work. Constants (const) stay narrow because they never change.

Key Takeaway: TypeScript automatically widens literal types to general types like string or number when you use let or var, making reassignment possible while still maintaining type safety.