Using Types

In this lesson, we're going to learn how to use types in TypeScript

Using types#

I have talked briefly about types in TypeScript in the second module. In this lesson, we will use them practically. Open the project, and run npm start. We see nothing because there is no app.js file yet. Let's write our code inside app.ts and later, we will compile it to JavaScript.

We know that JavaScript has three primitive data types; number, string and boolean. JavaScript doesn't have float or decimal data type; all of these come under number data type. Let's create a constant, num, and give it a value 1, and another constant called num2 and give it a value 2. Let's also create a string constant, str, and give it a value, I am a string; and finally a boolean, bool, and give it a value, true.

TypeScript has a property called inference which is the ability to infer the data type. Now that we have assigned values to our constants, there is no need to give them a type explicitly; although, we can do that, but it will be overkill to do so. However, let's say it was let rather than const and we needed to change the value; let's change const to let. Now, if we hover over num, it has inferred the data type, number. If we try to give it a value string, it gives us an error and it says, Type string is not assignable to type number. It is happening because we are inside a TypeScript file. If it were a JavaScript file, there would have been no issues assigning another data type to the variable. Let's change the string const to let and try to change the data type to a number. Again, it gives us an error. I hope you understand what inference means. Let's change it back to const.



Start a new discussion. All notification go to the author.