Type Inference
In this page:
Basic Inference
When a variable is initialized with a value, TypeScript can infer its type automatically from that value without needing an explicit annotation. Writing let age = 25 gives age the inferred type number with no extra syntax required.
Example: Basic Inference
let age = 25; // inferred as number, no annotation needed
console.log(typeof age, age);
Inference with const
Constants also receive an inferred type from whatever value they're assigned, and because const values can never be reassigned, TypeScript can sometimes infer an even more specific literal type than it would for a similarly initialized let.
Example: Inference with const
const name = "Fixed"; // inferred as the literal type "Fixed", not just string
console.log(name);
Inference in Arrays
TypeScript can infer the element type of an array directly from the values placed inside its initializer, so const nums = [1, 2, 3] is automatically understood as a number[] with no annotation needed. Mixed-type array literals get inferred as a union of those types.
Example: Inference in Arrays
const nums = [1, 2, 3]; // inferred as number[]
console.log(nums);
Inference in Expressions
Types are also inferred from the result of expressions and operations, such as the return type of a function being inferred from whatever its return statement actually produces. This lets you skip annotating return types on simple functions while TypeScript still keeps them fully checked.
Example: Inference in Expressions
function add(a: number, b: number) {
return a + b; // return type inferred as number
}
console.log(add(2, 3));
Inference and Explicit Types
Type inference reduces the need for unnecessary explicit annotations, keeping code less cluttered, while explicit annotations remain useful when you want to clearly document an intended type or deliberately restrict a variable to a narrower type than TypeScript would otherwise infer.
Example: Inference and Explicit Types
let count = 5; // inferred, no clutter
let id: number = 5; // explicit, documents intent
console.log(count, id);
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: