DEVELOPMENT by Pedro Resende

Why you should use TypeScript

On you're next JavaScript Project

Post by Pedro Resende on the 26 of August of 2020 at 19:50

Tags: developmentTSTypeScriptJSJavascript

For the last six months, I`ve been working on a JavaScript Full-Stack project, using React.js as the front-end framework, GraphQL for the API Gateway and Hapi Server for the micro-service which is connected to a Postgres RDS Database and during this time I had the pleasure for being able to work with TypeScript.

Advantages

You may ask what's the advantage of using TypeScript, another framework, instead of pure JavaScript which is more than enough. Well... it's quite simple, imagine all the power of the well known JS with the advantage of a typed language like C#, Java, or even PHP. 

But the reality it's that you can start moving slowly from JavaScript to TypeScript, that's one of the main advantages, another one is the integration with you're editor, which will infer correctly the type of a given variable, function input or output and in the end, it's all compiled to pure JavaScript which is simply perfect.

Basic Types

Let's start by seeing what are the Basic Types available:

Boolean

const booleanValue: boolean = false;

Number

const number: number = 12;

String

const someString: String = "This is a string";

Array

const array: number[] = [1, 2];

Tuple

const x : [string, number] = [a , 1];

Enum

enum Type {

  WATER,

  ELECTRICITY,

  GAS,

}

Type::WATER

Unknown

let x: unknown = 4;

x = "string";

Any

const xpto: any = "Can be anything";

Void

const xpto = (): void => {console.log("some message")}

Never

const xpto = (): never => {throw new Error("Some Error")}

Has you can see there is plenty of types to be with, and in the case of doubt you can set it to "any".

Convert from JavaScript to TypeScript

Imagine you have the following JS file

const add = (a, b) => a + b;

console.log(add(1,2));

it's quite a simple example, but I believe it's enough to be with, in TS you've had 

const add = (a: number, b: number): number => a + b;

console.log(add(1,2));

which is exactly the same, but if in my editor, which currently it's vscode, I make the mistake of typing

console.log(add("x", 2));

I'll have the following warning

Argument of type '"x"' is not assignable to parameter of type 'number'.

which is quite nice and the number of small issues will be reduced.

What do you think about TypeScript?