TypeScript · Lesson 6 of 120
Type Inference
TypeScript works it out.
You don't have to write every type. When you give a variable a value straight away, TypeScript works out its type for you. That's called inference.

- No label needed
- TypeScript guesses
- Inference
Inferred types still count
We give city a text value, with no type label. TypeScript infers it's a string. So putting a number in it later is still an error. Run it. Line two is rejected, just as if we'd written the type.
app.tstypescript
let city = "Leeds"; // inferred: string
city = 42;
console.log(city);Output
app.ts line 2: Type 'number' is not assignable to type 'string'.
When to write types
Let TypeScript infer simple variables with values. Write types for function parameters, because nothing else says what they are. And write them when a variable starts empty, or when you want to be extra clear.
| Situation | Write the type? |
|---|---|
| let x = 5 | no, inferred |
| Function parameters | yes |
| Empty to start | yes |
| Public APIs | yes, for clarity |
Summary
TypeScript infers types from values, so you only write them where they help. Next, the basic types.
Key takeaways- Inference
- Still checked
- Write where it helps
Next up: Basic Types — string, number, boolean