Ad

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

Why you should learn TypeScript and ditch JavaScript? TypeScript vs JavaScript

|
787

You aren't married to JavaScript, doesn't matter how much you love it, you must give it a try to TypeScript. Maybe you don't have a reason to move, but I will definitely take you on a journey, where you'd like to taste TypeScript a bit. I can give you more than 13 Reasons Why you should move to typescript, but for now, I'll try to convince you to move on to TypeScript in 5 points where I will tell you why TypeScript is much better than JavaScript for development, and why you should choose TypeScript for your next project.

1. Strictly Typed JavaScript

strictly-typed

Photo by Matt Artz on Unsplash

TypeScript is nothing but just a strictly typed javascript. One of the reasons I hate JavaScript (yes I hate it) is that there's so much flexibility on the language that there's no rules and regulation, you can write any crap, and it won't give you an error (exceptions are there), for example, if you created a variable and gave it some number as value say 6, later you can assign some function to the same variable, and can even call that variable, it seems a bit funny to me, anyway, let's see what TypeScript has to do with it.

In typescript, when you're defining a variable, you have to write its type, like the variable is going to store number, array, string, or anything else. Once you did it, you cannot store anything else in it or TypeScript won't let you proceed, and TypeScript is strict about it.

let age:number;
age = 25;

Even if you don't mention the type to the variable and assigning it some value, it is too smart, that it automatically find out the type from the value given and remembers it.

let age = 10;

age = "Donald Trump"
~~~
// Type '"Donald Trump"' is not assignable to type 'number'.(2322)

If you are aware of the languages like C/C++, there, the type is defined as int age; similarly, in TypeScript, we define type after the name of the variable following a colon sign, like this let age:number;. That way we just stuffed TypeScript without altering JavaScript syntax. That's what I told in the beginning, TypeScript is nothing just JavaScript, with just types. I will not focus on the syntax of typescript, it is not in the scope of this article.

Now, if it would be JS, you could do anything with the age, assing it your name, or some array, or even some function, but in TS, once it is born as number, it will remain number, nothing else. If you do it, it will give you error right away, but in JS, it will tolerate it as long as you're not doing something illegal, like calling age without assigning it a function or accessing .length property when it is a function.

At first, it might seem to you of not worth switching from JS to TS, but once you understand it completely, you never wanted to code in JS because of just this feature.

2. Because you need errors.

you need error

Photo by Sarah Kilian on Unsplash

When I say you need errors, doesn't mean I want you to write errorful codes, but the code you've written must be error-free, and for that, it is the job of your dev environment to give you errors. And in JS, it just doesn't do it, it is one of the reasons people love it, and at the same time hate it too. When I say errors, I mean everything except syntax errors. JS doesn't give an error when you write something wrong, but it gives you an error when something wrong happens. So if some part of your code isn't executed at the time of testing, then be ready for some pain in the production. :)
Let's see an example

I'm writing a code to multiply two numbers, I'll do this in both JS and TS, and you'll see how JS is so unreliable and may break your application in many ways.

function multiply (num1, num2 ) {
    return num1 * num2;
}

console.log(multiply(3, 4));
// returns 12

console.log(multiply(3));
// return NaN

console.log(multiply(3, null));
// returns 0

console.log(multiply());
// returns NaN

You can literally call multiply in any manner, there's no restriction, and it always gives you unexpected results, that's the worst thing about JS, suppose now you have to use those returned values somewhere, how much inconsistency and unexpected results it causes in your application.

But thanks to TypeScript, it is very strict, it won't let you proceed if you do not follow the rules if the function expects the, then you must pass the number, and it says both should be numbers, then you have to pass two arguments and both must be numbers. Let's see the same code in TypeScript. If you're not aware of the TS syntax, don't worry, it is similar to JS, except the return type comes before the opening brace and argument types with their names.

function multiply (num1:number, num2:number) :number{
    return num1 * num2;
}

console.log(multiply(3, 4));
// returns 12

console.log(multiply(3));
//          ~~~~~~~~~~~
// Expected 2 arguments, but got 1.(2554)
// input.tsx(1, 33): An argument for 'num2' was not provided.

console.log(multiply(3, null));
//                      ~~~~
// Argument of type 'null' is not assignable to parameter of type 'number'.


console.log(multiply());
//          ~~~~~~~~~~~
// Expected 2 arguments, but got 0.(2554)
// input.tsx(1, 20): An argument for 'num1' was not provided.

So here in TS, there are never unpredictable results, you can only proceed when you remove all the errors, that's what makes me fall in love with TS <3 

TS is not just bound to tell the errors in your code that you've written, but it also tells you the possibility, of where an error may come. Let's see a quick example of this.

// I'm writing some TS code, you can ignore it and look at the comment, I've written in the code.

// Type is user
interface User {

    // Property is name of type string
    name: string;

    // Property is age of type number
    age: number;

    // Property is social which is optional and have properties
    social?: {

        // Property is facebook which and have type string which is optional
        facebook?: string;

        // Property is twitter which and have type string which is optional
        twitter?: string;
    }
}

Now as you can see, the social property is optional means there may be cases where social is undefined, TS knows that, and it will not let you proceed until you handle it.

let userData:User = dataFromSomeSource;

console.log(user.social.facebook);
//          ~~~~~~~~~~~
// Object is possibly 'undefined'.(2532)

if(user.social){
    console.log(user.social.facebook);
}

So, this is silently ignored by JS, and it causes errors from case to case, which is another reason why TS is considered more reliable.

3. Auto Tested and Documented.

auto tested and documented

Photo by Jesus Kiteque on Unsplash

Suppose you're using a function from some library written in JS, how would you know what params you've to pass? You will go to the documentation, you'll check what params it will take, which of them are optional, and then you'll call the function. But in TS, there's no need to document that, everything is explained by the types themselves. Even it also ensures that you're using the function in the right way, and not passing any random parameters. 
For example, you can refer to the second section above.

Another case you can take is, suppose you're using a library that gives you a JS object, with nested properties, so to check what exactly the names of the properties, and which of them can be undefined, is a big pain. You have to dig in the documentation, or sometimes console log your object to see what stuff it contains. That's really what I hate, I wish some way, where the object itself tells you what properties it contains and if some property is undefined, or property has a value string or number or array or what. Well, the wish is fulfilled, thanks once again to TypeScript. If the codes are written in TS, the exact behaviour you'll get. Let's see with an example.

function getUser ( id: number ):User {
    // Some logic to get the user from id.
    let user:User = {name: "Bob", age: 24};

    return user
}

let user: User = getUser(1);

Now to check what properties the user will have, no need to console log it, or go to the function definition when you add an . after user, it automatically gives you the list of properties it has, and also tells you which of them are undefined. See the image below.

auto complete examle

It also automatically tests your codes by checking all the possibilities and tells you if any of the possibility fails. Sounds amazing right, well yes, it is. This feature prevents a huge number of bugs at the time of development, you don't need to write a test for your function nor need to test it manually at different values, TS do it for you and tells you if you've missed something that may cause a problem later.

In the code below, I have written a function that takes two arguments and returns an array of string by adding each parameter to the array if they are not undefined. The first argument is required while the second is optional.

function arrayFy (name1:string, name2?: string): Array<string> {
//                                                ~~~~~~~~~~~~~
// Function lacks ending return statement and return type does not include 'undefined'.(2366)

    let resultArray = [name1];

    if(name2) return resultArray.push(name2);
//            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type 'number' is not assignable to type 'string[]'.(2322

}

The code above is a very common scenario for me to make a mistake. Array.push does not return the updated array, but returns the new length of the array. So if the above code is written in the JS, there won't be any error, and my code just runs and gives expected results, which I have to debug and find the mistake here, and my function is returning 2 if I pass the second argument too. But here in TS, you can clearly see that TypeScript automatically run the case, and tell you that in that particular case, your function will fail to return an array of strings. 

There's another error, say if you don't pass the second parameter, you're still returning nothing (undefined), which also violates the behaviour of your function as it must return an array of strings. So, here I made some changes in the function and TS gives you a green flag, which means the function will never ever give you an unexpected result. See below.

function arrayFy (name1:string, name2?: string): Array<string> {

    let resultArray = [name1];

    if(name2) {
        resultArray.push(name2);
    }

    return resultArray;

}

4. Always a few steps ahead of JavaScript

typescript ahead of javascript

Photo by Kayvan Mazhar on Unsplash

Typescript is always a few steps ahead of Javascript. If a new feature is announced in JavaScript, and it is supposed to be released in the next ECMA release, TS release it before the official release and you can use it without any worries of compatibility in browsers as you can compile TS to any previous version of JavaScript (like ES5). TypeScript has a lot of features that JavaScript doesn't.

So we can say that TypeScript is also a superset of JavaScript, ECMA5, ECMA6, ECMA7 and ECMAnext, and some features that don't even exist in JavaScript.

5. Conclusion: You can't run away from TypeScript

can't run away from the typescript

Photo by Chris Yang on Unsplash

Yes, sooner or later, you have to accept TypeScript. You just can't run away from it. Every npm package either being written in JavaScript has to provide its types too, or another package with typescript support is preferred. Now, most of the large libraries, packages, and frameworks are being written in TypeScript.

In the beginning, packages used to be in JavaScript with TypeScript support too, but now the table has turned, and packages are in TypeScript and they are giving support to JavaScript. Everyone is acknowledging the power and need for TypeScript over JavaScript and accepting it.

You'll never be able to learn Angular, as it forces you to write only TS code, the same case with the loopback 4. NestJS primary language is TypeScritpt and they also provide support for JavaScript. Following are the words of NestJs

We're in love with TypeScript, but above all - we love Node.js. That's why Nest is compatible with both TypeScript and pure JavaScript. Nest takes advantage of the latest language features, so to use it with vanilla JavaScript we need a Babel compiler.

If you're still not satisfied with the reasons I gave you, and have some counter questions, you can anytime contact us, and believe me, it is worth giving a try, you won't regret it.

Ad


Comments

© 2024 Garbage Valuegarbage value logo