Type Inference in Arrays and Objects
What you'll learn: When TypeScript correctly infers array and object types from literals, and when you need explicit annotations to prevent unwanted type widening.
The Inference Sweet Spot
When you write array or object literals, TypeScript infers their types immediately from the values you provide. This usually works great:
const numbers = [1, 2, 3]; // inferred as number[]
const mixed = [1, "two", true]; // inferred as (number | string | boolean)[]
const user = {
name: "Alice",
age: 30
}; // inferred as { name: string; age: number }
TypeScript looks at what you wrote and says "I see numbers, so this is a number[]" or "I see these specific properties with these types."
When Inference Widens Too Much
Problems arise when TypeScript infers a broader type than you intended:
let config = {
mode: "development" // inferred as string, not "development"
};
// Later, this succeeds but might be wrong:
config.mode = "any random string"; // allowed!
Using let causes the literal "development" to widen to string. With empty arrays, TypeScript can't infer anything useful:
const items = []; // inferred as any[] (if noImplicitAny is off)
Preventing Unwanted Widening
Use explicit annotations when you need stricter types:
const config: { mode: "development" | "production" } = {
mode: "development"
}; // mode is now locked to these two values
const items: string[] = []; // explicitly typed empty array
Key Takeaway: TypeScript infers array and object types from literals well, but use explicit annotations when you need narrower literal types or when initializing empty collections to prevent type widening.