Type Inference (TypeScript)

Type inference is TypeScript's ability to figure out a type automatically from the value you assign, without you writing an annotation. If you write `let x = 5`, TypeScript already knows x is a number.

TypeScript

Inference keeps TypeScript code concise: you get full type checking without annotating every variable. The general advice is to let TypeScript infer local variables and only add explicit annotations where it can't, such as function parameters.

Once a type is inferred, it still applies. Even though you never wrote `: number`, reassigning that variable to a string is a compile error.

Examples

TypeScript — Compile error: Type 'string' is not assignable to type 'number'.

let score = 10;   // inferred as number
let city = "Rome"; // inferred as string
score = "high";

Learn it in a lesson

See also

Back to the Dictionary