Lost Precision with Intermediate Variables
What you'll learn: How assigning values to intermediate variables can widen their types and lose important specificity.
The Problem
When you store a literal value directly in a variable, TypeScript infers a broader type than the literal itself. This widening becomes a problem when you later pass that variable somewhere expecting the more specific type.
Think of it like pouring fresh orange juice into a generic "beverage" pitcher. Once it's in there, all you know is "it's some beverage"—the "definitely orange juice" specificity is lost.
How Precision Gets Lost
// Direct use: TypeScript sees the literal "GET"
fetch('/api', { method: 'GET' }); // ✓ Works
// Intermediate variable: widens to string
let method = 'GET';
fetch('/api', { method }); // ✗ Error: string not assignable to specific methods
// The fix: annotate or use const
const method: 'GET' = 'GET'; // or just const narrows it
fetch('/api', { method }); // ✓ Works again
The first example works because 'GET' stays a literal type. The second fails because method has type string, but fetch expects specific literal strings like 'GET' | 'POST'. The variable assignment widened the type, losing the precision.
Why It Happens
Variables declared with let are mutable, so TypeScript assumes you might reassign them. It infers a broader type to allow flexibility. But this flexibility costs you the specificity needed for strict APIs.
Key Takeaway: Intermediate variables widen literal types to their primitive types by default. Use const declarations or explicit type annotations to preserve the specific literal type when precision matters.