TypeScript Tutorial

By Xah Lee. Date: . Last updated: .

This page shows you the most basic use of TypeScript to compile ES2015 JavaScript to ES5 JavaScript.


goto https://www.typescriptlang.org/download/

Filename Extension

TypeScript filename extension is “.ts”.

For example, create a JavaScript file with the following content:

const f = (x => [x + 1]);
const m = 4;
document.body.innerHTML = f(m);

Name the file “test.ts”.

Compile to JavaScript

in terminal, type

tsc test.ts

it will create a file of same name ending in “.js” in the same directory.

ES2015 to target ES5 Flags

TypeScript has flags that control how you want the ouput.

Here's basic flag config for compiling to ES5:

# TypeScript basic config for compiling to ES5 js
tsc --target ES5 test.js

Here's basic option for compiling to ES2015:

# TypeScript basic config for compiling to ES2015 js
tsc --target ES2015 --alwaysStrict test.js

--alwaysStrict means add "use strict" in output source file.


You might get errors such as

 error TS2322: Type 'any[]' is not assignable to type 'string'.

but don't worry about type errors. It'll still compile.

Currently, we are only interested in compiling ES2015 js to ES5.

later on, you can add types to your JavaScript so the errors don't show. Or, add declarations to suppress some errors.

Features TypeScript Won't Translate

TypeScript only does syntactic transformation.

Things it does not compile to ES5 are ES2015 objects.

For example:

When you have these objects, TypeScript leaves them as is.