Const vs Let: Inference Differences
You'll learn: How const declarations produce narrower, more precise inferred types compared to let and var.
The Core Idea
When TypeScript infers a type, it makes assumptions about whether you'll reassign that variable later. With const, TypeScript knows the value can never change, so it infers the most specific type possible — the literal value itself. With let or var, TypeScript assumes you might reassign it, so it infers a broader type that accommodates future changes.
Same Value, Different Inference
const greeting = "Hello"; // Type: "Hello" (literal)
let message = "Hello"; // Type: string (wider)
Both variables hold "Hello", but TypeScript sees them differently:
greetingis typed as the literal"Hello"— that exact string, nothing elsemessageis typed asstring— any string value
Why This Matters
const status = 200; // Type: 200
let code = 200; // Type: number
// Later in your code:
code = 404; // ✅ Fine, it's a number
// status = 404; // ❌ Would error: can't reassign const
The narrower const inference helps TypeScript understand your intent. When a value is 200, not just some number, TypeScript can catch mistakes where you accidentally use the wrong specific value.
The Analogy
Think of const as a locked box with a label showing exactly what's inside. let is an unlocked box labeled with what type of thing it holds, but the contents might change.
Key Takeaway: Use const by default to get the most precise type inference — TypeScript will lock in literal types instead of widening to string, number, or boolean.