Introducing TypeScript

TypeScript is an open source, gradually typed superset of JavaScript created and maintained by Microsoft. It was created to allow developers to supercharge the JavaScript language and to also make it easier to scale applications. Among its main capabilities is providing typing to JavaScript variables. Types in JavaScript enable static checking, thus making it easier to refactor the code and find bugs. And at the end, TypeScript compiles to simple JavaScript code!

Regarding the scope of this book, with TypeScript, we can use some object-oriented concepts that are not available in JavaScript such as interfaces and private properties (this can be useful when working with data structures and sorting algorithms). And of course, we can also leverage the typing functionality, which is very important for some data structures.

All of these functionalities are available at compile time. Once we write our code, we compile it to plain JavaScript (ES5, ES2015+, and CommonJS, among other options).

To get started with TypeScript, we need to install it using npm:

    npm install -g typescript

Next, we need to create a file with the .ts extension, such as hello-world.ts:

let myName = 'Packt'; 
myName = 10; 

The preceding code is a simple ES2015 code. Now, let's compile it using the tsc command:

    tsc hello-world

On the Terminal, we will get the following warning:

hello-world.ts(2,1): error TS2322: Type '10' is not assignable to type 'string'. 

But if we verify the folder where we created the file, we will see it created a hello-world.js file with the following content:

var myName = 'Packt'; 
myName = 10; 

The previously generated code is ES5 code. Even with the error in the Terminal (which is in fact a warning, not an error), the TypeScript compiler generated the ES5 code as it should. This reinforces the fact that although TypeScript does all the type and error checking during compile time, it does not prevent the compiler from generating the JavaScript code. This means that developers can leverage all these validations while we write the code and get a JavaScript code with less chances of errors or bugs.