Type inference

Until now, the illustrated code included the type information in the same statement where the actual value assignment took place. TypeScript supports type inference, meaning that it tries to resolve the relevant type information if you don't specify any.

Let's look at some examples:

const count = 2;

In the preceding simple example, TypeScript is smart enough to realize that the type of count is a number without you having to explicitly specify that:

function sum(x1: number, x2: number) {
return x1 + x2;
}

const mySum = sum(1, 2);

The preceding example demonstrates the power of type inference in TypeScript. If you pay close attention, the code doesn't specify the return value type of the sum function. TypeScript evaluates the code and determines that the return type is number in this case. As a result, the type of the variable mySum is also a number.

Type inference is an extremely useful feature since it saves us the incredible time that would be otherwise spent in adding endless type information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.152.159