TypeScript Tutorial

By Xah Lee. Date: . Last updated: .

2016-10-30 my learning notes.

this page shows you the most basics of using TypeScript to compile ES2015 JavaScript to ES5 JavaScript.

install

# instal
npm install -g typescript

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

# TypeScript compile file to js
tsc test.ts

ES2015 to target ES5 Flags

TypeScript has flags that control how you want the ouput.

Here's basic flag config for compiling ES2015 to ES5.

# TypeScript basic config for compiling ES2015 to ES5 js
tsc --alwaysStrict --lib DOM,ES2015,DOM.Iterable,ScriptHost --target ES5 test.js

Errors

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 js so the errors don't show. Or, add declarations to suppress some errors.

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