The Widening Problem Without as const
You'll learn: How TypeScript automatically relaxes specific literal values into general types, often losing useful precision.
What Is the Widening Problem?
When you declare a variable with let or var, TypeScript assumes you might reassign it later. To give you flexibility, it widens the literal value to its base type. A string like "admin" becomes string, and a number like 42 becomes number.
This widening happens automatically, and while it's often convenient, it can cause problems when you actually want to preserve the exact literal type.
Why This Matters
let role = "admin";
// Type: string (not "admin")
type UserRole = "admin" | "user" | "guest";
function checkRole(role: UserRole) {
// ...
}
checkRole(role);
// Error: Argument of type 'string' is not assignable to parameter of type '"admin" | "user" | "guest"'
Even though role holds "admin", TypeScript widened it to string. Now it's too general to match the precise union type UserRole.
The Mutable Variable Assumption
TypeScript reasons: "You used let, so you might change this later to any string." To avoid restricting you, it picks the broader type. This is usually helpful for variables you'll reassign, but unhelpful when you want specificity.
const status = "success";
// Type: "success" (literal preserved with const)
let mutableStatus = "success";
// Type: string (widened because it's mutable)
Key Takeaway: Without as const or const, TypeScript widens literals to their base types (string, number, boolean), sacrificing type precision for reassignment flexibility.