...

/

Understanding type inference

Understanding type inference

Adding type annotations to our code means we need to write extra code which consumes our time and bloats our code. TypeScript has something called type inference which means, in many cases, it can work out a variable's type without it having a type annotation. In this lesson, we'll learn how and when we can use type inference.

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:

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:

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 ...