Why should you use TypeScript over JavaScript?

Akash Gupta
GDSC KIIT
Published in
7 min readMar 6, 2021

--

Image from TSH(The Software House)

TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript.

Stricter programming languages will inform the developer when they change one area of code in a way that will break other areas. JavaScript will not, which often leads to unexpected behavior at runtime.

To address these shortcomings, Microsoft developed TypeScript and released it publicly in 2012 to blend the flexibility of JavaScript with the advantages of a stricter language.

According to the 2020 Stack Overflow Developer Survey, TypeScript is the second most loved language by developers.

Image from StackOverflow

This article will give you a brief overview of the benefits that TypeScript offers. Although it has plenty of useful features, we will keep it short and discuss only the basic ones.

TypeScript’s main benefits:

Consider the JavaScript code :

let division = true;
let dividend = 6;
if (division) {
dividend = "three";
}
let result = dividend/ 3;
console.log(`Division result is: ${result}`);
prints: "Division result is : NaN"

Our code has a bug 🙀! We need to inspect our code and fix it. It looks like we’re assigning the wrong type of data to dividend. Change the assigned value of dividend to be the expected value with the correct type.

The snippet above has only a few lines of code, so we were able to fix this within no time but what if we are dealing with huge a codebase and happen to face a problem like this. It would be very tedious to look through the codebase and find the error.

Don’t worry :) this is when TypeScript comes into play.

TypeScript Type Inference

Type inference assumes the expected type of the variable throughout a program based on the data type of the value initially assigned to it at declaration. Type inference will log a complaint if the variable is later reassigned to a different type.

let name = 'Zack Snyder';

name = 1067; // Type 'number' is not assignable to type 'string'

TypeScript Supports Type Annotations

Adding a type annotation ensures that a variable can only ever be assigned to that type. This can be useful when declaring a variable without an initial value. Type annotations get removed when compiled to JavaScript. The type declaration is provided by appending a variable with a colon (:) and the type (eg. number).

let name: string;
name = 'Zack Snyder';

// Error: Type 'number' is not assignable to type 'string'
name = 1067;

Functions

When we declare a function in JavaScript, we often expect it to be invoked with arguments of a certain type. JavaScript does not share our expectations, its type flexibility often allows functions to be invoked with unexpected argument types. Even when this doesn’t result in errors, there can be negative consequences:

function lengthOfText(text) {
console.log(text.length);
}

lengthOfText(5); // Prints: undefined

Although we can approach error-handling solutions to avoid such undesirable effects, these techniques can be cumbersome:

function lengthOfText(text) {
if (typeof text !== 'string') {
throw new Error('Argument is not a string!');
}

console.log(text.length);
}

lengthOfText(5); // Error: Argument is not a string!

In the code above, the function first checks the argument type. If it doesn’t match the expected type, an error is thrown; otherwise, it continues with its intended operation.

We can handle the above code very neatly with TypeScript using the TypeScript Function Parameter Type Annotations.

Function parameters may be given type annotations with the same syntax as variable declarations: a colon next to the name. The type annotations ensure that the parameters are of the correct type:

function lengthOfText(text : string) {
console.log(text.length);
}
lengthOfText(5); // Argument of type '5' is not assignable to parameter of type 'string'.

Explicit Return Types

If we’d like to be explicit about what type a function returns, we can add an explicit type annotation after its closing parenthesis. Here, we use the same syntax as other type annotations, a colon followed by the type. TypeScript will produce an error for any return statement in that function that doesn’t return the right type of value.

function createGreeting(name: string): string {
if (name) {
return true; //Typescript Error: Type 'true' is not assignable to type 'string'
}
};

Consider the JavaScript Code:

import {getUserChoice,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12} from './resources'function returnVehicle() {let num = getUserChoice();switch(num) {  case 1 : return f1();  case 2 : return f2();  case 3 : return f3();  case 4 : return f4();  case 5 : return f5();  case 6 : return f6();  case 7 : return f7();  case 8 : return f8();  case 9 : return f9();  case 10 : return f10();  case 11 : return f11();  case 12 : return f12(); }
return 'Tesla.jpg'
}
console.log(returnVehicle())

The function getUserChoice() gets a user’s vehicle choice entered as a number from 1 to 12. Then, returnVehicle() runs a vehicle-generating function (f1() through f12()) to return a filename '<vehiclename>.jpg'.

export function f1() {
return 'Volvo.jpg'
}
...
...
...
export function f12() {
return 'Jaguar.jpg'
}
...
...

Imagine only 11 out of 12 of the functions f1() through f12() correctly return a vehicle.jpg filename and one function has a faulty return value of type number but we don’t know which function it is? It would be a nightmare to have to look through all that source code! Let TypeScript do the work for you.

As all the functions are expected to return a value of type string, annoying the function returnVehicle( )as string type will handle the problem.

import {getUserChoice,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12} from './resources'function returnVehicle(): string {let num = getUserChoice();switch(num) {  case 1 : return f1();  case 2 : return f2();  case 3 : return f3();  case 4 : return f4();  case 5 : return f5();  case 6 : return f6();  case 7 : return f7();  case 8 : return f8();  case 9 : return f9();  case 10 : return f10();  case 11 : return f11();  case 12 : return f12(); }
return 'Tesla.jpg'
}
console.log(returnVehicle())
TypeScript Error

Yeah 😲 !!! TypeScript found the problematic function for us. Now we can just navigate to the f9() function in the codebase and fix its return value.

export function f1() {
return 'Volvo.jpg'
}
...
...
...
export function f9() {
return 57772; //Change it to string type
}
...
...

TypeScript Type for One-dimensional Array

The type annotation for a one-dimensional array in TypeScript is similar to a primitive data type, except we add a [] after the type.

// employeeName is an array of strings
let employeeName: string[] = ['Zack', 'John', 'Mando', 'Robert'];

// Pushing a number to employeeName will generate an error
// Error: Argument of type 'number' is not assignable to parameter of type 'string'.
employeeName.push(90210);

Consider the JavaScript code:

This is a small piece of code from a company’s codebase

let employeeArray = ['Steve', 'Mark', 'Joseph', 3432434, 'Mary'];function checkEmployeeArray() {
for (let i = 0; i < employeeArray.length; i++) {
if (typeof employeeArray[i] != 'string') {
console.log(`Type error: ${employeeArray[i]} should be a string!`);
}
}
}
checkEmployeeArray()
function stringPush(val) {
if (typeof val === 'string') {
employeeArray.push(val);
}
}

The employeeArray stores the employee’s names that are working under the company. It will crash the entire system if employeeArray is found to contain any data of the number type!

The functioncheckEmployeeArray() checks that every element of employeeArray is a string.

The stringPush()function that takes one argument: val, the value meant to be pushed into the array. The function should check if the val is a string and .push() it into the employeeArray array only if it is a string.

Sadly 😥 even with all this, people could ruin your precious string array by writing code like employeeArray[3]=3

But don’t worry we got TypeScript there to help us out 💪

The same code in TypeScript can be written as :

let employeeArray : string[] = ['Steve', 'Mark', 'Joseph', 3432434, 'Mary']; // TypeScript Error: Type 'number' is not assignable to type 'string'

Now we no longer need thecheckEmployeeArray() function to check that every element of employeeArray is a string or the stringPush()function to verify if an element is a string before pushing it into the array. TypeScript does most of the work for us ❤

TypeScript offers so many functionalities that it becomes a good alternative to JavaScript.

If you have a huge project that you are working on alone or along with several developers, TypeScript is the best alternative.

I hope you found this article to be helpful. If you’d like to learn more, I encourage you to check out the resources below.

Useful Links :

Thanks for reading! If you enjoyed this article, please click the 👏 button and share to help others find it! Feel free to leave a comment 💬 below.
Have feedback? Let’s connect on
Twitter.

--

--