Typescript

Transpilation

Since browsers don’t know about Typescript we need to convert it into something they do understand.

The current version of javascript with the broadest support across browsers is still ES5 so that’s what we are currently converting 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.

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.t.

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

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

tsc -w

If we are compiling a single file we must provide all the 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 watching a whole directory we can use a configuration file.

We can create a config file with our common settings so we don’t always have to provide them

tsc --init

This creates a default configuration file which we can edit later on.

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.

results matching ""

    No results matching ""