Type inference is TS guessing types from usage so you write less. It looks at: • Initializers (const/let) • Return statements • Default params • Contextual positions (e.g., callbacks) Let it infer obvious things; annotate public surfaces or when inference is too broad.
let variable = value; // Type inferred from valuelet name = "Alice"; // string
let nums = [1, 2, 3]; // number[]
let mixed = [1, "two"]; // (number | string)[]
function double(x: number) {
return x * 2; // return inferred number
}
const names = ["Ada", "Linus"];
names.forEach((n) => n.toUpperCase()); // contextual typing: n is string
// Too broad without initializer -> any
let data;
data = "string";
data = 42;
// Safer
let safeData: unknown;
// must narrow before useUnderstanding Type Inference is fundamental to mastering TypeScript. Practice with the examples above and experiment with variations to solidify your knowledge.