TypeScript inferring types

Hi, in the last post we saw how to configure TypeScript in our project and in this post I wan to show you how TypeScript inferring types for us.

Let ‘s see this code example:

let a = 1 + 2;
let b = a + 3;
let c = {
  watermelon: a,
  apple: b,
};
let d = c.apple * 4;

Now if I made a hover over the variables we can see how TypeScript will show us the type of the variables, in this case I’m hovering over the “a” variable and see how TypeScript says: hey! the “a” variable is number type.

Cool, next if I made a hover over the “watermelon” property we can see how TypeScript say: hey! this is a property called watermelon and the type is number.

Nice, now if I made a hover over the “apple” then TypeScript say: hey! the “apple” property is a property and is a number type!

And this is because “apple” property of the “c” object is also a number

Now I made a hover over the variable “d

Nice! now, if we insert non-existent object or variable then TypeScript will show a red squiggly under that object or variable – this is known as “throwing a TypeError

If I made a hover over the “x” TypeScript say: Hey! cannot find name “x” and this makes sense because we never declared the “x” in our code.

Then If I insert a string in the multiplication then TypeScript will say: hey! the type of that side need to be ‘any’, ‘number’, ‘bigint’ or ‘enum’. – this means that we cannot insert a string in this section.

If you saw the examples you can realize that TypeScript is inferring the types for us and let us now when some type is wrong.

By Cristina Rojas.