Say hello to TypeScript


Introduction

In short, TypeScript is a superset of JavaScript that has optional typing and compiles to plain JavaScript.

In simpler words, TypeScript technically is JavaScript with static typing, whenever you want to have it.

Installation

Installing TypeScript is as simple as running the following command in our Terminal:

npm i -D typescript

The above command installs TypeScript as a dev dependency in our project. We can also install it globally using:

npm i -g typescript

Why TypeScript?

There are many reasons why we should use TypeScript but the most important ones are:

  1. TypeScript is more reliable
  2. TypeScript is more explicit
  3. Easier to refactor code without breaking it significantly.
  4. TypeScript and JavaScript are practically interchangeable, so why not?

How to use

Once we have TypeScript installed, we can start writing TypeScript files which have the extension .ts

// File: helloWorld.ts

const greeting = 'Hello world!';
👉

We can write any JavaScript code in our TypeScript files and that will be a valid TypeScript code.

What TypeScript allows us to do is we can add type definition to our code which then checked to insure we have type safety in our code.

// File: helloWorld.ts

const greeting: string = 'Hello world!';

const year: number = 2021;

We cannot directly execute our TypeScript code directly in the browser so we need to compile it down JavaScript first.

Our typescript page also gave us access to a TypeScript compiler. If you installed it locally, we can access it as

node_modules/typescript/bin/tsc

and can compile our file down to JavaScript

node_modules/typescript/bin/tsc helloWord.ts

It will generate a helloWorld.js file in our project. Here's what this new file contains:

// File: helloWorld.js

const greeting = 'Hello world!';

const year = 2021;

We can also pass some options to our tsc command or alternatively create a tsconfig.json file in our project. You can learn more about the options here in official documentation.

👉

This was just a basic introduction to TypeScript and in the next post, we will learn about different types in TypeScript.