Type inference
The compiler figuring out types automatically, without you writing annotations.
Example
#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)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
#let count = 0
// TypeScript infers: numberMore examples
#const ids = []
// type: any[] (without strict) or never[] in some contexts
const scores: number[] = []
scores.push(90)
console.log(scores)[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
#- string, number, booleanThe basic primitive types: text, numbers, and boolean values.
- Literal typesTypes that allow only specific values, e.g. "easy" | "hard".
- Function typesTyping parameters, the return value, and functions themselves as values.
- NoInfer<Type>Blocks inferring a type parameter from a given spot, so other arguments determine the type.
Spotted a mistake or missing an example? Write to us.