Type Inference
Prerequisites: Type annotations
TypeScript can often figure out a variable's type automatically from its initial value, without you writing an annotation at all.
let name = "Ada"; // inferred as string, no annotation needed
name = 42; // Type 'number' is not assignable to type 'string'
Even though no : string was written, TypeScript still enforces it —
inference determines the type once, at declaration, and then treats it
the same as if you'd written it explicitly.
Common mistakes
- Declaring a variable without an initial value and expecting a type
to be inferred —
let x;infers the very permissiveanytype, losing type-checking forxentirely. Give it an initial value or an explicit annotation.