Why you should use Typescript?

Why you should use Typescript?

Could it be the best way to write the JavaScript application in 2022?

As a full-stack Software Engineer and working in the industry for the last 4 years there was always something missing in the puzzle and that was security in Javascript applications for me. I didn't know what is security in JavaScript applications and how can we handle it. there was a lot of talking in the air around TypeScript and I was kinda afraid to jump into it but one day I worked on a very simple javascript calculator and there were a lot of issues I ran into 5 lines of code. I was shocked, disgraced, and questioning my experience and skillset but after a very little search I found out Typescript is the solution for the issue I am facing. In This Article, I will explain What type of calculator was working, what kinda Issue I faced, how I solved these using typescript, and argue you to use TypeScript.

What is Typescript?

I couldn’t start this article without at least a short explanation of what Typescript exactly is. Typescript is an open-source programming language created by Microsoft. Actually, it’s a superset of Javascript which adds types to Javascript. It is worth mentioning that in the end Typescript compiles to Javascript, so the final code can run on any environment which supports JS.

Now you could ask:

“Ok, but why do I need static typing at all? If Typescript compiles to Javascript doesn’t it mean that Javascript is enough?”

Exactly the question I had and when I searched what is special in TypeScript, the first thing I read was that I give JavaScript Power like Strictly Type languages which don't make sense clearly and I always skipped finding the exact answer. I Just use JavaScript to make things work and was thinking that learning TypeScript may make you hurt so why should we?

Why I Start Learning TypeScript?

As I said earlier I had no interest in Learning TypeScript but then in mid-2021 During Covid Time I was spending more time at home on weekends and was doing basic projects to make myself busy. I just started to add functionality to Basic Calculator from my college days. The UI was pretty cool but most of the functionality was broken, I will take a simple add function to explain how TypeScript helped me to update it.

The Issue

Let's take a simple add function, open your favorite IDE and create an index.html file with the following content

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Simple Add Calculator</title>
  </head>
  <body>

    <input type="number" id="num1" placeholder="Number 1" />
    <input type="number" id="num2" placeholder="Number 2" />
    <button>Add!</button>

    <script src="index.js" defer></script>
  </body>
</html>

Simple HTML UI with two Inputs and a button, you will get the following output when you run the code in the browser

Screenshot 2022-01-20 at 1.18.31 PM.png

Now let's add some JavaScript to add basic functionality, create an index.js file in the same directory and add the following piece of code

const button = document.querySelector("button");
const input1 = document.getElementById("num1");
const input2 = document.getElementById("num2");

function add(num1, num2) {
  return num1 + num2;
}

button.addEventListener("click", function() {
  console.log(add(input1.value, input2.value));
});

Pretty Simple and straight forward right? Let's test it but adding 53 and 25 which should be 78

Screenshot 2022-01-20 at 1.22.03 PM.png

Wait what? Everything Looks fine and as per WC3 Standards I have put

input type="number"

but still doesn't work...

ryan-reynolds-but-why.jpeg

The issue is somehow the input pass the data as a string and it adds two strings instead of two Numbers. Now As we know the actual issue, let's find a better solution to fix it forever.

let's Bring In TypeScript

As we Know JavaScripy Type Conversions can be very confusing and to override this we can use typeScript. It's very simple to Setup and Install TypeScript on your local machine. after installation lets jump into the terminal and run

tsc --version

this will make sure TypeScript is installed and ready to use. let initiate a new project using

npx tsc --init

and it will create a tsconfig.json file with all the setup required.

The directory will now have 3 files

  • Index.html

  • Index.js

  • tsconfig.json

let's add a new file index.ts, .ts extension to make sure it has access to TypeScript with the following code

const button = document.querySelector("button")! as HTMLInputElement;
const input1 = document.getElementById("num1")! as HTMLInputElement;
const input2 = document.getElementById("num2")! as HTMLInputElement;

function add(num1: number, num2: number) {
  return num1 + num2;
}

button.addEventListener("click", function() {
  console.log(add(+input1.value, +input2.value));
});

Almost the same JavaScript but some new terms from typescript, which are

Pretty interesting, isn't it? that with simple 4 keywords we can say everything is safe and secure to run. But as I mentioned earlier we still need to compile it to Javascript. to do compilation we need to run the following command in the same directory

tsc --build

it will rewrite the index.js file with the following compiled code

"use strict";
const button = document.querySelector("button");
const input1 = document.getElementById("num1");
const input2 = document.getElementById("num2");
function add(num1, num2) {
    return num1 + num2;
}
button.addEventListener("click", function () {
    console.log(add(+input1.value, +input2.value));
});

We moved to Typescript, we updated the code but does it work? let test

Screenshot 2022-01-20 at 1.58.53 PM.png

Yes, it does and it works as per the requirements. but the question arises that isn't it almost the same Javascript code that was before, so how TypeScript handle the type Checking

why-use-typescript-typescript-meme_.png

Typescript improves project quality

Software projects are different and often involve more than one developer to contribute. All these things I mentioned in previous sections lead to better and easier project maintenance. Developers can really appreciate all TypeScript flavors when their project grows and the team goes bigger.

Even if the project is small and requires only one developer on the front end and one on the backend, it’s so much simpler for other developers to hop in or take over the project when code is self-explanatory. Choosing Typescript by default also forces developers to think in a more data-driven style. When a project starts or a new feature comes into play, we create types, interfaces and think about data shape from the beginning. Because of this approach, very often you can spot and solve problems much earlier than in JavaScript.

Shall I Use TypeScript In my Projects.

Of course yes, If all of the mentioned arguments didn’t convince you to use TypeScript to write the frontend in 2022 I can just refer to “big players” on the market. Typescript is supported by the most popular Javascript libraries and frameworks and more are trying to support it day by day. Modern Frontend Frameworks like Angular Vue React and Svelte Support TypeScript, on backend Node express Loopback feathers, WebSocket, NestJS, and GhrapQL support TypeScript. So...

waiting.jpeg

According to Stackoverflow 2021, Survey Typescript is 2nd Most wanted languague and 4th on Worked with vs. want to work with and last but no the least Better Paying than Java (Suprise 😱), JavaScript and C++.

Why might you not like Typescript?

I couldn’t exclude Typescript disadvantages from this article. Like every technology, Typescript has its cons too. For me, these are not big concerns at all but I understand that for some developers, it's better to give an overview of some major cons.

Typescript can be difficult (at the beginning!)

When you switch from a dynamic language like javascript it can be difficult to start a new project in this technology. You probably think: “OMG, now I have to write much more code than I would write in vanilla JS”. Additionally, the first contact with TS errors may leave you scared or surprised, or maybe both. sometimes they are really hard and long to read indeed. But trust me, after some time you will appreciate this additional effort when your project grows or when you have a long break from it.

Typescript is not 100% reliable

Now you’re probably thinking: “Wait… But you said that….”, so let me explain. Typescript is just another tool in the world of software development that people use to achieve better results in software projects. But people make mistakes. Some libraries or project files can have wrong type definitions. If you use popular open-source packages or libraries this happens very rarely, and even if does, you can check out GitHub issues or create a new issue by yourself. If you find a bug in type definitions you can even make a pull request by yourself to help this library grow. so the reliability is not from the language but from the human and you know humans always make mistakes.

Typescript is not used everywhere

You already know that some types might be faulty, but I have one more surprise – there are packages and libraries (maybe one of your favorite) that don’t have type definitions at all. Very often libraries or packages have their own types inside them, but sometimes they just don’t exist. Fortunately, there is a huge repository Definitely Typed where you can check if your package misses any type of definition. 90% will exist and you’ll be ready to go. However, a few times I’ve managed to choose some less popular plugin or library which was lacking in types, or maybe you can jump in and try to contribute to the library.

Why use TypeScript to write the Apps in 2022? Summary

As you can see, Typescript has its pros and cons. Although, Typescript disadvantages are minor enough, and the overwhelming advantages it offers are completely worth it. That’s why I choose Typescript by default for my new software projects for all clients. The article you've just read deals with practical code examples of why should you use typescript and I think I have put enough aspects and arguments to use typescript.

Conclusions

Overall, TypeScript is a great tool to have in your toolset even if you don’t use it to its full capacity. It’s easy to start small and grow slowly, learning and adding new features as you go. TypeScript is pragmatic and welcoming to beginners, so there is no need to be afraid. I hope this post will be useful in your TypeScript journey and you hopefully you learnt something.