Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are ES6 features compiled to ES5 when used within TypeScript?

When I use ES6 features like for example template string, arrow functions, destructuring within a TypeScript file. Afterward I compile the file to normal JavaScript ...

Are the ES6 syntax compiled too by the TypeScript compiler? Or do I have to use an additional compiler (Babel)?

like image 715
cluster1 Avatar asked Dec 06 '25 19:12

cluster1


1 Answers

Are the ES6 syntax compiled too by the TypeScript compiler? Or do I have to use an additional compiler (Babel)?

I disagree with the Fylax's answer. The TypeScript compiler doesn't require an additional tool for converting the ES6 syntax to ES 3 or 5.

The TypeScript compiler tranpiles the new syntax (let, for … of, arrow functions, rest parameters, etc.) to ES 3 or 5. But it doesn't provide any polyfill by itself. In order to use a recent API (like Promise) on a old VM ES 3 or 5, you have to:

  1. Load a polyfill (like es6-promise) that makes the API available;
  2. Say the compiler to use the standard typings for this API.

It is a robust design option. With typeScript, you have to choose carefully the polyfills you need, and to test them on the different browsers you target.

By default, when the target is ES 3 or ES 5, the compiler doesn't use the definitions for the recent ECMAScript API. See the documentation:

Note: If --lib is not specified a default library is injected. The default library injected is:

► For --target ES5: dom,es5,scripthost

If a polyfill makes an API available, then we can configure the compiler to use it. Here is an example of configuration file tsconfig.json for using promises on ES5 VM:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "es5", "es2015.promise"]
  }
}

However, Babel can convert a few more features to ES 5 than TypeScript does. See the compatibility table from Kangax.

like image 103
Paleo Avatar answered Dec 08 '25 07:12

Paleo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!