How Type Inference Works
Type inference is the compiler deriving a type from an initializer, return expression or surrounding context. An annotation supplies an explicit type where needed.
Compare inferred types at initialization, reassignment and function boundaries.
New TypeScript users often annotate everything: let count: number = 0, const title: string = "Buy milk". It works, but it is noise. The compiler can already see those types. Knowing what it infers tells you exactly where annotations earn their place.
The rule
Where there is a value, TypeScript infers; where there is none, you annotate.
Inference means the compiler works out a type from the code around it.
let count = 0; // number
const status = "open"; // "open" (a literal type)
let tags = ["home", 1]; // (string | number)[]
function makeTask(title: string) {
return { title, done: false };
}
// return type inferred: { title: string; done: boolean }Notice the difference between let and const. A let variable can be reassigned, so TypeScript widens 0 to the general type number. A const can never change, so it keeps the exact literal type "open". For an array of mixed values it infers an array of a union — "each element is a string or a number".
Inference also flows into callbacks. This is called contextual typing:
const ids = [3, 1, 2];
ids.map(n => n * 2); // n is number, because ids is number[]The place inference cannot help is a function parameter with no default value. Nothing in the function tells TypeScript what callers will pass, so title would silently become any. With the noImplicitAny check (part of strict mode) that is an error, which is why parameters are the main thing you annotate.