Typescript Basics

Typescript Basics


TL ; DR , Simply Typescript is the superset of javascript. TypeScript is an open-source programming language developed and maintained by Microsoft.

Javascript is the weakly or dynamically typed language.

To understand let’s write some javascript code:

var x = 0;

x = “Hello”;

Here x is number but we have assigned the string, it works fine in javascript context.

For statically typed languages like java my favorite one, this is not the case. We need to specify the type of the variable at the time of declaration itself.

int x = 0;

x = “Hello”; //This will give compilation errors.

That's why for compile-time type safety people has introduced Typescript.

We need the compiler like BABEL to convert typescript into the javascript.

To add typescript globally, use npm and run this command on the terminal as:

npm install -g typescript

This will add the tool globally.

Now to use it,

Create the typescript.ts file in any of your favourite editor like VS code, Sublime etc.

Write code as:

const addition = (x: number, y: number): number => {return x + y;}

const answer = addition(5, 6);

Now run this command on the terminal as:

cmd> tsc typescript.ts

BABEL will generate a typescript.js file.

See, the ECMA5 code which is supported by almost all browsers.

var addition = function (x, y) { return x + y; };

var answer1 = addition(5, 6);

We cannot run typescript directly on the browser as browsers don’t understand typescript.

Run it using node,

cmd> node typescript.js

It will output 11.

Typescript does strict type checking if you run below code:

var addition = function (x, y) { return x + y; };

var answer1 = addition('Hello', 6);

This will fetch error on your terminal as:

typescript.ts:9:26 - error TS2345: Argument of type '"Hello"' is not assignable to parameter of type 'number'.

Even editors like VSCode will show red underline for the erroneous code.

That’s it!!! We can use very well popular open-source programming language for our projects for frameworks like NodeJS , ReactJS , AngularJS .

Note: Use Definitely typed for typescript to understand JS frameworks types.