TypeScriptBasic types

Type inference

The compiler figuring out types automatically, without you writing annotations.

On this page

Example

#
TypeScript
const lessons = [
  { title: 'HTML', minutes: 12 },
  { title: 'CSS', minutes: 15 }
]
// type: { title: string; minutes: number }[]

const totalMinutes = lessons.reduce((sum, l) => sum + l.minutes, 0)
// type: number

const titles = lessons.map((l) => l.title.toUpperCase())
// type: string[]

console.log(totalMinutes, titles)
Result
27 ['HTML', 'CSS']

Definition and usage

#

In many places, TypeScript figures out the type on its own by looking at the value. The declaration let count = 0 gives a variable of type number, and a function that returns a + b for two numbers has the inferred return type number.

That keeps the code from being overloaded with annotations. Good practice is to type the boundaries, meaning function parameters, public APIs, and data from outside, and leave the rest to inference.

You can see the inferred type in the editor by hovering over the variable. If it’s different from what you expect, add an annotation, so the compiler reports the mismatch right where it originates.

Syntax

#
Syntax
let count = 0
// TypeScript infers: number

More examples

#
When inference isn’t enough
TypeScript
const ids = []
// type: any[] (without strict) or never[] in some contexts

const scores: number[] = []
scores.push(90)
console.log(scores)
Result
[90]

Good practices

#
  • Give an explicit type to empty arrays and objects that you fill in later.
  • Hover over variables in the editor. It’s the fastest way to see what the compiler inferred.

Related entries

#

Spotted a mistake or missing an example? Write to us.