Destructuring Inference Limitations
What you'll learn: Why destructured variables sometimes lose the precise type information that TypeScript would otherwise infer.
When you destructure objects or arrays, TypeScript tries to infer types for the new variables based on the source's type. However, the inference engine often picks a wider type than what the original value had, causing you to lose precision.
The Core Problem
Imagine you have an object with a specific property value. When you destructure that property into a standalone variable, TypeScript doesn't always carry over the exact literal type—it widens to a more general type instead.
For example, if you destructure a property that's the literal "admin", TypeScript might infer the variable as string rather than the specific "admin" literal. This happens because destructuring creates a new binding, and TypeScript's widening rules kick in, assuming you might reassign it later.
Why This Happens
Think of it like making a photocopy: the original document (your source object) has perfect clarity, but the copy (your destructured variable) loses some detail in the process. TypeScript assumes destructured variables are meant to be flexible, so it widens their types unless you explicitly tell it otherwise.
The Solution
When you notice destructured variables losing type precision, you can restore it by adding explicit type annotations to the destructured variables themselves, or by using as const on the source object to prevent widening in the first place.
Key Takeaway: Destructuring often triggers type widening—destructured variables get broader types than their source values, requiring explicit annotations or as const to preserve precision.