The Wonders of TypeScript

TypeScript was created by Microsoft in 2011 and has been a hit ever since. Many large projects and enterprise applications have utilized it in their front end. TypeScript is also interchangeable with JavaScript. This makes it a great language to learn if you already know JavaScript. TypeScript is a pleasure for larger projects due to the fact that it has static typing. Static typing allows programmers to catch errors much quicker. Often with Vanilla JavaScript errors will only show up during run time. However, with TypeScript these errors can be weeded out before running your code. Your errors will be shown before you can run your code.

Red underlined code displays errors before running your code.

Find out for yourself! Let’s install TypeScript right now. Create a new project and enter the following inside your terminal. You will need a copy of Node.js as an environment to run the package. Then you use a dependency manager like npm to download TypeScript.

npm install typescript -g

Now that you’ve installed typescript go ahead and create a file called hello.ts, once you’ve done so paste this code into the file.

export {};

Now once this code is in we’ll try to run it to see if we can get the terminal to output “Hello World”. Usually with javascript we would normally enter this into the terminal

node hello.js

However with TypeScript we need to enter this to run our code

tsc hello.ts

After running this script you’ll notice something interesting, an almost identical file is created. The only difference is that it is a .js file and not a .ts file. This is due to the fact that TypeScript is a superset of JavaScript. Another difference is that the function does not state the type that the variable being passed in is. In the TypeScript file it establishes that the text is a string but in the JavaScript file it doesn’t. This is one of the perks that TypeScript provides as we can now declare types when we pass in a variable like so. If you were to now change the variable text to a number and run the code, you will get the following error.

hello.ts:7:31 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

To finish off and to see your console display “Hello World” make sure you change the variable text back to a string and run

node hello.js

Of course there’s plenty more that TypeScript has to offer but this should be a good way to get an understanding of TypeScript before tackling what else is out there. Stay tuned for more articles in the future as I go deeper into TypeScript.

Recent graduate actively seeking full time opportunities. https://www.linkedin.com/in/vakas-akhtar-a4bb30170/