#native_company# #native_desc#
#native_cta#

TypeScript Setup


Transpilation

Since browsers don’t know about TypeScript we need to convert our TypeScript code into something they do understand.

The current version of JavaScript with the broadest support across all browsers is still ES5, so that’s what we currently convert our TypeScript code into.

The process of converting TypeScript into ES5 is called transpilation and we use a tool called tsc to compile on the command line.

Note

It’s useful to have the tsc tool so you can try out TypeScript yourself and transpile on the command line but it’s not necessary to do this in your everyday Angular development.

Projects built using the Angular command-line tools use the webpack bundler which handles transpilation of your TypeScript for you.

It is good however to have tsc installed especially if you want quickly try our some TypeScript features and see how they are transpiled into ES5 or ES6.

Installing TypeScript

We can install TypeScript via npm

npm install -g typescript

The preceding command will install the TypeScript compiler and add its executable tsc to your path.

To make sure everything worked correctly type:

tsc -v

And it should print something like

Version 1.8.0

Running TypeScript

Create a file called hello.ts.

Inside that file add console.log('hello world');

We can compile a TypeScript file into a JavaScript file by calling:

tsc hello.ts

This generates a file called hello.js

And we can execute that file by using node, like so:

node hello.js

We can watch a TypeScript file for changes and compile it automatically with:

tsc -w hello.ts

We can provide configuration on the command line, like so:

tsc -t ES6 -w hello.ts

Tip

The above -t ES6 is a flag to tell TypeScript to transpile into ES6 instead of the default ES5.

However if we are want to watch a whole directory we need to use a configuration file.

We can create a config file with the most common settings like so:

tsc --init

If we want to watch all files in a directory we can just type:

tsc -w

Warning

If there are errors, by default TypeScript will still output the JavaScript file if it can, this behaviour can be changed in the config.

Caught a mistake or want to contribute to the book? Edit this page on GitHub!



Advanced JavaScript

This unique course teaches you advanced JavaScript knowledge through a series of interview questions. Bring your JavaScript to the 2021's today.

Level up your JavaScript now!