Advantages of TypeScript

Edison Devadoss
3 min readJul 31, 2021

--

Hi friends, In this article, I will explain about advantages of TypeScript.

https://www.photopea.com

We all know TypeScript is the superset of JavaScript. TypeScript is strongly typed.

Browsers do not understand TypeScript. It understands only JavaScript. TypeScript code is converted to JavaScript code via the TypeScript compiler. It runs as JavaScript code in browsers.

Advantages of TypeScript

I will give advantages of TypeScript with an example. It precisely explains about how TypeScript is helpful to developers.

https://carbon.now.sh

In the above example, I add two numbers using function. In the first log, I pass two values “5”, 5 as arguments. The first argument type is a string so It concatenates two values. It gives 55 but I expected 10.

Here we are not checking the type of the parameters so whatever comes it just adds. But (+) operator do two things. It can add numbers and concatenates strings.

So in the above example (“5” + 5) returns 55.

That is a logical error.

If we want to avoid this error we need to check the type of each argument.

https://carbon.now.sh

In the above image, Before add, I check the type of the arguments. If the type of two values is a number then I add two numbers. Otherwise, I convert string to number then adds two numbers. Now it returns (“5”, 5) is 10.

But this approach is too complicated. We need to write a lot of code. In this approach, we can not write readable code.

Then What is the solution?

TypeScript is the solution. TypeScript helps us to catch errors. Using TypeScript we can write clean code add avoid bugs.

Install TypeScript in the machine

$ npm install -g typescript

For compile TypeScript file

$ tsc app.ts

The tsc generates a JavaScript file in the same name of the file with .js extension.

https://carbon.now.sh

In the above image, I have set the type for the parameters. It allows only the type of number.

Compile TypeScript

Screeenshot

While compiling (tsc app.ts) it throws an error. Because we set type for parameters.

https://carbon.now.sh

Now I fixed the error. It compiles successfully.

If we pass two numbers (5, 5) only compile successfully.

Typescript is really helpful to write better code.

Thank you for reading. Have a nice day!

https://www.typescriptlang.org/

--

--

Edison Devadoss
Edison Devadoss

Written by Edison Devadoss

Software Engineer / Full Stack Developer / JavaScript / React / React Native / Firebase / Node.js / Book Reader

No responses yet