If you are a newer JavaScript developer like me you may have come across the superset of JavaScript known as TypeScript. TypeScript is an open-source extension of JavaScript that changes JavaScript from an object-oriented scripting language into a object-oriented programming language. It does this by adding types to JavaScript. But you may be asking what's the point of adding types to JavaScript? Well the main benefit from doing so is that it makes it a whole lot easier to catch errors in development. The problem with JavaScript is that an error generally happens on the client side of things rather than on the developer side of things. TypeScript solves this issue by letting you compile your code in your IDE before testing it out. If you've ever written vanilla JavaScript you know how big of a deal this is, so let's go check it out!

Setting Up TypeScript

None

To get started using TypeScript the first thing you want to do is install it globally by running the npm command: npm i -g typescript . After that let's quickly make a index.ts file with the following code:

None

What I am doing here is defining a new object called TechBlogger using TypeScript's keyword interface. An interface is basically a way to make sure that our object has strict types. This means that I can only pass a string for name, and a number for id. Now we are going to test this code by running tsc index.ts and you'll see that we get an error:

None

This is because we made our id a string instead of a number, and because we are using TypeScript it actually threw us in error in our local terminal. You may notice that the other thing TypeScript did when we compiled it was that it created an index.js file:

None

This is because TypeScript is not a replacement for JavaScript, but a superset and so it uses babel to convert all of its code into vanilla JavaScript. One thing you may have seen when looking at this code is that it looks like old JavaScript. This is because TypeScript defaults to ES3. Luckily for us there is an easy fix to this:

None

First make a file called tsconfig.json and then write the code shown above. This will not only make it so that it compiles to the latest version of ES, but the "watch" option will make it so that you compile every time you save instead of having to write tsc. Ahhhh much better:

None

Conclusion

And that's it! You have written your first few lines of TypeScript and you hopefully now have a better understanding of what it is, and the benefits of using it. Happy coding!

Sources:

https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html