Using const for Literal Narrowing
You'll learn how const declarations preserve exact literal values as types, while let widens them to general primitives.
The Core Idea
When you declare a variable with let, TypeScript assumes you might reassign it later, so it widens the type to the broader primitive category. But when you use const, TypeScript knows the value can never change—so it keeps the exact literal value as the type instead.
Think of it like labeling a box: let says "this box can hold any number," while const says "this box holds exactly the number 42, forever."
How It Works
let flexibleNumber = 42;
// Type: number (could be any number)
const fixedNumber = 42;
// Type: 42 (exactly the literal 42)
let flexibleString = "hello";
// Type: string (could be any string)
const fixedString = "hello";
// Type: "hello" (exactly the literal "hello")
With let, TypeScript widens 42 to number and "hello" to string because you could reassign them. With const, it preserves the literal types 42 and "hello" because reassignment is impossible.
Why This Matters
Literal types are more precise. They let TypeScript catch mistakes where you accidentally use the wrong specific value. This becomes especially powerful later when working with things like configuration objects or strict value sets.
Key Takeaway: Use const when you want TypeScript to remember the exact literal value as the type, giving you narrower, more precise type checking.