Kuan Kuan - 1 month ago 9
TypeScript Question

Relationship between TypeScript and ES6

All:

I am pretty new to Typescript and ES6, the first thing confuses me is their relationship, from MSDN:


TypeScript 1.5 adds a number of new ES6 features including modules,
destructuring, spread, for..of, symbols, computed properties,
let/const, and tagged string templates.


My confuse is(I know there are lots of posts say that the Typescript is the superset of JS):

Dose this mean TypeScript just use its own way( some slightly diff syntax and transpile) to redo what already exists in ES6 again( just for type purpose ),

and

Does it mean ES6 basically can do everything that in TypeScript? and vice versa

Answer Source

TypeScript is a script code that is transpiled to JavaScript - either to ES5 or ES6 (and ES3 too).

TypeScript 1.5 adds a number of new ES6 features including modules, destructuring, spread, for..of, symbols, computed properties, let/const, and tagged string templates.

This means that you can use modules, for..of and other features in your TypeScript code and TypeScript compiler transpiles your code to ESx compatible code that does the same thing. Let's take for..of for instance:

TypeScript code:

for (let t of [1,2,3]) {
    console.log(t)
} 

is transpiled to ES5 like this:

for (var _i = 0, _a = [1, 2, 3]; _i < _a.length; _i++) {
    var t = _a[_i];
    console.log(t);
}

However, if you target ES6, then the transpilation is simply:

for (let t of [1,2,3]) {
    console.log(t);
}

The same holds for modules, spread, etc. In each case TypeScript generates code that behaves the same in ES5, ES6 and ES6 (it's simplified because it's not always possible).

There is not difference in expressivity of TypeScript and ES6. The difference is that TypeScript compiler helps you with static analysis of your code. Otherwise, whatever you can program in ES6, you can program in TypeScript and the other way around.