Variable inference
Concept and syntax
When an initializer makes the type clear, TypeScript can infer the type without a colon annotation. let count = 3 normally infers number and later assignments must fit number. Inference is not the same as any; the inferred type still restricts operations. Use an explicit annotation when the intended set of values is broader or narrower than the initializer suggests.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
let count = 3;count = 5;let label = "tea";console.log(count, label.toUpperCase());Expected output (one line per log):
5 TEACommon mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS2322. The initializer established number, not any. Keep assignments numeric or declare an intentional wider type.
Practice and recap
Infer a number and a boolean from initializers, then try one compatible and one incompatible assignment for each.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variable inference — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
What is inferred for let count = 3?
When is an explicit annotation useful?
Which assignment works with the inferred type of count?
let count = 3;count = "five";