Course contentsShow
← TypeScript
Lesson 98 of 1,7963. Basic TypesFree lesson

Primitive Type Widening on Reassignment

See how TypeScript widens types when variables are reassigned to different values.

Primitive Type Widening on Reassignment

What you'll learn: How TypeScript changes a variable's type from a specific literal to a broader primitive when you reassign it.

When you first declare a variable with let or var and assign it a literal value, TypeScript infers the most specific type possible. But once you reassign that variable to a different value of the same kind, TypeScript realizes the variable isn't locked to one specific value—it can hold any value of that broader type.

How It Works

let status = "active"; // Type: "active" (literal)
status = "inactive";   // Now type widens to: string

In the first line, TypeScript thinks: "This variable holds exactly the string 'active'." But when you reassign it to "inactive", TypeScript realizes you intend to use this variable for different string values, so it widens the type from the literal "active" to the primitive string.

The same happens with numbers and booleans:

let count = 0;    // Type: 0 (literal)
count = 5;        // Type widens to: number

let flag = true;  // Type: true (literal)
flag = false;     // Type widens to: boolean

Why This Matters

Think of it like a box labeled with its first item. Once you put a different item of the same kind in, the label changes from "the red ball" to just "a ball." TypeScript is being practical: if you're reassigning, you probably need flexibility.

This widening only happens on reassignment. If you never reassign, the type stays narrow.

Key Takeaway: TypeScript widens a variable's type from a specific literal to the broader primitive type when you reassign it, reflecting your intent to store varying values.