Careeroza
Type Annotations vs Inference
TypeScript Can Infer Types
You do not need to annotate everything. When you initialise a variable, TypeScript infers its type from the value.
Example
Hover over these variables in VS Code: count is number, label is string. const values get an even narrower literal type like "INR".
let count = 5; // number
let label = "Items"; // string
const currency = "INR"; // type is the literal "INR"
const prices = [10, 20]; // number[]
count = count + 1;
console.log(label, count, currency, prices.length);Output
Items 6 INR 2
Inference Still Protects You
Example
Even without an annotation, count is a number, so assigning a string is an error.
let count = 5;
count = "six";Compiler output (tsc)
Line 2: error TS2322: Type 'string' is not assignable to type 'number'.
When to Annotate
| Situation | Annotate? |
|---|---|
| Variable initialised with a value | no, let TypeScript infer |
Variable declared without a value (let total;) | yes, otherwise it may become any |
| Function parameters | yes, always |
| Function return types | optional; recommended for exported / public functions |
Empty arrays ([]) | yes: const ids: number[] = [] |
Tip: A good rule: annotate the boundaries (function inputs and outputs, API data) and let inference handle the inside.