Array and Object Literal Inference
You'll learn: How TypeScript automatically figures out the types of arrays and objects based on the values you write.
The Core Idea
When you create an array or object with literal values, TypeScript looks at what you've written and infers the types without you having to explicitly annotate them. It's like TypeScript saying, "I see numbers in this array, so this must be a number[]" or "I see a name property with a string value, so this object has a string property called name."
Array Literal Inference
When you write an array literal, TypeScript examines the elements:
const ages = [25, 30, 42]; // Inferred as: number[]
const names = ["Alice", "Bob"]; // Inferred as: string[]
const empty = []; // Inferred as: any[] (no evidence to work with)
TypeScript picks the common type among the elements. If you mix types, you get a union:
const mixed = [1, "two", 3]; // Inferred as: (number | string)[]
Object Literal Inference
For objects, TypeScript infers a property-by-property structure:
const user = {
name: "Alice",
age: 30
};
// Inferred as: { name: string; age: number; }
Each property's type is inferred from its value. The object's shape becomes its type.
Key Takeaway: TypeScript infers array types from their elements and object types from their properties, automatically creating precise types from literal values without requiring explicit annotations.