Preventing Widening with Type Annotations
You'll learn how to lock in literal types by explicitly telling TypeScript what type you want, stopping it from widening to a broader primitive.
The Problem: Widening Strikes Again
In the previous lesson, you saw how let variables widen from literal types ("success") to broader primitives (string). This happens because TypeScript assumes you might reassign the variable, so it gives you flexibility. But sometimes you want the literal type preserved—you need TypeScript to treat "success" as only "success", not just any string.
The Solution: Type Annotations
When you add an explicit type annotation, you're telling TypeScript: "This is the exact type I want, don't make assumptions." For literal types, this means the value stays narrow.
// Without annotation: widening happens
let status = "success"; // Type: string
// With annotation: literal type preserved
let status: "success" = "success"; // Type: "success"
Now status can only ever be "success". If you try to assign "failed" to it, TypeScript will error—because you've locked it to that specific literal.
When This Matters
This technique is crucial when building discriminated unions, function parameters that accept only specific values, or configuration objects:
let direction: "up" | "down" = "up";
direction = "down"; // ✓ OK
// direction = "left"; // ✗ Error: Type '"left"' is not assignable
Analogy: Think of it like labeling a box. Without a label (let x = 5), TypeScript assumes it's a general "numbers box." With a label (let x: 5 = 5), you've marked it "only 5s allowed."
Key Takeaway: Use explicit type annotations (: "literal") to prevent widening and preserve the exact literal type you need.