Type Annotations
Prerequisites: Basic types
A type annotation is the : Type you add after a variable, parameter,
or function to state exactly what it should hold.
Real-world analogy: a type annotation is like a label on a storage bin at a warehouse — "screws only" — so anyone (including a future version of you) instantly knows what's supposed to go there, and a mislabeled item gets caught immediately.
Syntax
let variableName: Type = value;
Example
let score: number = 95;
score = "ninety-five"; // Type 'string' is not assignable to type 'number'
Common mistakes
- Over-annotating everything, even when TypeScript can already tell —
let age: number = 25is redundant;let age = 25infersnumberautomatically (see the next lesson). Annotate where the type isn't obvious from the value, like function parameters.