This video is available to students only

Using TypeScript

In this lesson, we're going to add typescript file to our project

In the last lesson, you saw how the sum function concatenated the inputs rather than adding them. However, there is a simple fix; just add + sign in front of the inputs, and it will treat them as a number. But it's not an optimal solution, because you'll have to do this wherever the values are being used. This is where TypeScript comes handy.

Let's create a TypeScript file in the same directory and let's call it scripts-ts.ts; you can name it anything. Just make sure the extension is .ts. Now let's copy the entire JavaScript file to the TypeScript file. We see some errors; don't worry, this is what we want to fix. Before fixing that though, let's delete scripts.js file. We see some errors are gone because we are not using the same declarations in two different files. We do see some errors here, because TypeScript is not sure if the input 1 and input 2 have some values inside them.

TypeScript is not wrong because a lot of html tages don't have value associated with them, so we'll have to be explicit about it. To tell TypeScript that the input will never be empty and it will yield some value, we can use an exclamation mark in front of the inputs. We also know that it's an input element, but TypeScript doesn't know that; it doesn't validate the html elements. So to tell TypeScript that it's an input element, we can be explicit about it by writing as HTMLInputElement. Now we see that the errors are gone, because we have told TypeScript that these are the input values and they are not going to be null. This is called typecasting, where we explicitly inform about the nature of the element.

Also, we are able to use the exclamation mark and the typecast because this is a TypeScript file and not a vanilla JavaScript file; JavaScript doesn't understand that.

This lesson preview is part of the The newline Guide to Fullstack ASP.NET Core and React course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to The newline Guide to Fullstack ASP.NET Core and React with a single-time purchase.

Thumbnail for the \newline course The newline Guide to Fullstack ASP.NET Core and React