Type inference means TypeScript works out a type from the code itself, so you don't have to write an annotation. A variable gets the type of its initial value, and a function's return type comes from what it returns.
let message = "Hello"; // TypeScript infers string type
let count = 42; // TypeScript infers number type
let isActive = true; // TypeScript infers boolean type
function add(a: number, b: number) {
return a + b; // Return type inferred as number
}
Inference keeps code short and still fully typed. Parameters are the main exception. Under strict, a parameter needs an annotation unless it has a default value or gets its type from context, as a callback does.
A let infers a wider type than a const: let x = "a" is string, but const y = "a" is the literal type "a".
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓