AI Hints
Home›TypeScript Tutorial›First Steps
TypeScript · Lesson 6 of 120

Type Inference

TypeScript works it out.

⏱ 2 min read▶ Video at 5:05🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

Type Inference
From the video: Type 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.

SituationWrite the type?
let x = 5no, inferred
Function parametersyes
Empty to startyes
Public APIsyes, 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