TypeScript: Convert to JavaScript

By Xah Lee. Date: . Last updated: .

How to Convert TypeScript File to JavaScript

For example, create a file with the following content:

// file name xx.ts

const f = ((x: number) => [x + 1]);
const m = 4;
console.log(f(m));

Name the file xx.ts

in terminal, type

tsc xx.ts

it creates a file of same name ending in .js in the same directory.

Specify Target JavaScript Version to Compile To

TypeScript compiler tsc has optional flags that specify which JavaScript version you want to compile to.

tsc --target targetTag filename

the targetTag can be:

ES5
the JavaScript before ES2015.
ES2015
The JavaScript version with massive major additions. [see JavaScript: 2015 Features]
ES2016, ES2017 etc are minor additions, every year.

Here's basic flag config for compiling to ES5:

# compile to pre-ES2015 js
tsc --target ES5 test.js

Here's basic option for compiling to ES2015:

# compile to pre-ES2015 js
tsc --target ES2015 --alwaysStrict test.js

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

WARNING: TypeScript Do Not Translate New Thing in JavaScript

The TypeScript compiler does not create code for a new type, object, or function in new JavaScript spec. When you have these objects, TypeScript leaves them as is.

For example, the JavaScript: Map Object is new in JS2015. If you are using it in TypeScript, and compile it to target ES5 (the JavaScript before 2015), The result code still contains the map object as is.