Lessons · TypeScript · inference
Types you did not write
The first assignment fixes a variable's type: let x = 3 makes x a number. A const gets the exact literal, so const y = 3 has type 3.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Most TypeScript has few annotations because inference does the work. Knowing what it infers explains why x = 'hi' fails and why a const string is narrower than string.
How to think about it
Hover, or reason: let widens to the general type, const keeps the literal. Annotate only when inference would be wrong or too wide, such as an empty array that will hold numbers.
Worked example
let x = 3;Inferred as number from the first assignment.
x = 7;Fine.
x = "hi";Error: string is not assignable to number.
const y = 3;A const can never change, so its type is the literal 3, not number.
Your turn
Reassign a string variable.
let city = "Leeds"; city = ;
Solve one with the compiler running
The trap
let items = [] infers never[] or any[] depending on settings. Annotate an empty array: let items: number[] = [].