Type Inference
Learn how TypeScript automatically infers types from context, reducing how often you need to write explicit annotations.
Reading Time
12 min
Lesson
Lesson 7 of 30
What is Type Inference?
TypeScript can often figure out a value’s type automatically from how it’s initialized, without you writing an explicit annotation at all.
Inference from Initial Value
let count = 10; // inferred as number
let name = "Alice"; // inferred as string
let isDone = false; // inferred as boolean
count = "ten"; // Error: Type 'string' is not assignable to type 'number'Inference in Function Return Types
TypeScript also infers a function’s return type from its return statements, so you often don’t need to annotate it explicitly.
Inferred Return Type
function add(a: number, b: number) {
return a + b; // return type inferred as number
}Contextual Typing
TypeScript can also infer types based on where a value is used — for example, callback parameters in array methods are typed automatically based on the array’s element type.
Contextual Typing in a Callback
const numbers = [1, 2, 3];
numbers.forEach((n) => {
// 'n' is automatically inferred as number, no annotation needed
console.log(n.toFixed(2));
});The best common type Algorithm
When an array contains multiple types, TypeScript infers a union type that covers every element.
Inferred Union Type
let mixed = [1, "two", 3]; // inferred as (string | number)[]Uninitialized Variables Infer as any
A variable declared without an initial value and without strict mode may be implicitly typed as any, silently losing type safety. noImplicitAny (included in strict mode) turns this into a compile error instead.
noImplicitAny Catches This
let value; // implicitly 'any' without strict mode
value = 5;
value = "now a string too"; // allowed with implicit any, which defeats the purposeBest Practice
Let inference handle simple local variables and return types. Add explicit annotations at your codebase’s boundaries — function parameters, exported functions, and public APIs — where inference has nothing to infer from.