What is type inference in TypeScript
· Category: TypeScript
Short answer
Type inference is TypeScript's ability to deduce types from values and context, reducing the need for explicit type annotations while maintaining safety.
How it works
When you assign a value, TypeScript infers the variable's type from that value. Function return types are inferred from the return statements. Generic functions infer type arguments from the provided parameters. Contextual typing occurs when a type is known from the surrounding context, such as event handler signatures.
Example
let x = 10; // inferred as number
function add(a: number, b: number) {
return a + b; // inferred return type: number
}
Why it matters
Relying on inference reduces boilerplate and keeps code readable. However, explicit annotations are valuable for public APIs, complex functions, and places where inference produces overly wide types like any[].