Variable Declaration: When to Annotate
You'll learn: When to explicitly type your const, let, and var declarations versus letting TypeScript figure it out for you.
The Golden Rule: Let Inference Work First
By default, TypeScript is excellent at inferring types from variable initializations. When you write const name = "Alice", TypeScript knows it's a string. Most of the time, you don't need to annotate at the point of declaration.
const count = 42; // TypeScript knows: number
let isActive = true; // TypeScript knows: boolean
const items = [1, 2, 3]; // TypeScript knows: number[]
When You Should Annotate
1. Declaring without initializing:
let userId: number; // No initial value = must annotate
// later...
userId = 123;
2. When inference produces something too narrow:
let status = "pending"; // Type: "pending" (literal)
status = "complete"; // Error! Can't reassign
let status: string = "pending"; // Better: allows any string
3. When you want a specific wider type:
const config: any = { theme: "dark" }; // Intentionally loose
const data: unknown = fetchFromAPI(); // Unknown for safety
The const Exception
With const, TypeScript infers literal types because the value can't change. This is usually what you want, so annotations are rarely needed.
const API_URL = "https://api.example.com"; // Type: the exact string
Key Takeaway: Prefer inference for initialized variables; annotate only when declaring without a value, when inference is too narrow for your needs, or when you intentionally want a different type than what would be inferred.