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.
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.)
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.
Yes. You can target TypeScript compiler to ES6.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With