Inference Limitations with Empty Values
You'll learn: Why TypeScript can't always infer useful types from empty arrays, objects, and null values, and what to do about it.
When you give TypeScript an empty value—like [], {}, or null—the compiler faces a dilemma: what type should it infer? There's no data to analyze, so it must make a conservative guess.
The Empty Array Problem
let items = []; // TypeScript infers: any[]
Without any elements to examine, TypeScript defaults to any[]—an array that can hold anything. This defeats the purpose of type safety! If you later push numbers and strings into it, TypeScript won't complain:
items.push(42);
items.push("hello"); // Both allowed with any[]
The Empty Object Problem
let config = {}; // TypeScript infers: {}
An empty object literal infers as {}, which means "an object with no known properties." You can't safely add properties later without type errors.
The Null Problem
let data = null; // TypeScript infers: null
Inferring null as the type means you can only assign null to this variable—it's permanently stuck!
The Solution: Add Type Annotations
When starting with empty values, help TypeScript by providing explicit annotations:
let numbers: number[] = [];
let config: { theme: string; debug: boolean } = {} as any; // (will learn better patterns later)
let data: string | null = null;
Think of it like telling someone to prepare an empty container: you need to specify what kind of container (shoe box? tool chest?) before they can gather the right one.
Key Takeaway: Empty arrays, objects, and null lack context for inference—TypeScript defaults to overly general or overly narrow types. Always provide explicit type annotations when initializing with empty values.