Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Typescript transpilation handle transpiling ES6 to ES5?

I am writing an app using Angular 2 and TypeScript. I want to use a js method (particularly 'filter' for arrays) which is supported by IE 11+, Chrome 45+, etc. Will my code be able to run on older browsers? As Typescript transpiles to vanilla js, I am not sure what it does with ES6 features.

like image 526
Alejandro B. Avatar asked Dec 15 '16 20:12

Alejandro B.


People also ask

Can TypeScript compile to ES5?

Luckily, TypeScript 2.1 now supports compiling asynchronous functions to ES3 and ES5. Just like the rest of the emitted code, they run in all JavaScript environments. (That even includes IE6, although I hope that you're not forced to support such ancient browsers anymore.)

How does Transpilation apply to TypeScript?

Typescript does transpile into Javascript. In your tsconfig configuration file, you can specify which is the target language you want it transpiled to. That means you can already work with cutting edge ECMAScript features out of the box.

Does TypeScript compile to ES6?

Yes. You can target TypeScript compiler to ES6.

What version of ECMAScript does TypeScript use?

TypeScript is a strict superset of ECMAScript 2015, which is itself a superset of ECMAScript 5, commonly referred to as JavaScript. As such, a JavaScript program is also a valid TypeScript program, and a TypeScript program can seamlessly consume JavaScript.


1 Answers

TypeScript allows you to use new language features from ES6 and it will transpile those language features to ES5; however, it does not add polyfills for built in functions that exist in ES6, but don't exist in ES5.

If you are using built in functions that only exist in ES6 and are targeting ES5, then you will need to include the necessary polyfills in order for the code to work in ES5 environments.

Example

For example, fill is a new function found on Array's prototype in ES6.

const result = ["first", "second"].fill("all");

When you target ES6 everything is fine. The compiler will include lib.es6.d.ts with the definition for fill and not complain because it assumes you will be running the code in ES6 environments where the fill function exists.

When you target ES5, however, it won't include lib.es6.d.ts and will tell you that function doesn't exist in ES5 environments:

error TS2399: Property 'fill' does not exist on type 'string[]'.

To fix that, you'll need to add fill to the Array<T> interface in a definition file in your project:

interface Array<T> {
    fill(value: T, start?: number, end?: number): this;
}

And include a polyfill. Or use something that does it automatically for you.

like image 55
David Sherret Avatar answered Oct 16 '22 23:10

David Sherret