Search⌘ K
AI Features

Understanding type inference

Explore how TypeScript automatically infers types for variables and functions to simplify your React code. Understand when inference works and the importance of type annotations for function parameters to write clearer and more maintainable code.

Using type inference on variable declarations #

TypeScript will automatically infer the type for a variable if a type annotation hasn’t been specified.

The code below declares a variable and initializes it with the value 10 without a type annotation:

TypeScript 3.3.4
let score = 10;

Hover over the score variable. What has TypeScript inferred the type to be?

So, TypeScript can automatically infer the type of a variable from the value it is assigned. Great!

Now look at another example below:

TypeScript 3.3.4
let dateOfBirth = new Date(1990, 4, 7);

What do you think TypeScript inferred the type to be?

So, TypeScript can infer types that don’t exist in JavaScript. Neat!

Let’s look at the type of a variable defined ...