Search code examples
typescripttargettranspiler

What will Typescript transpile when targeting ES5 / ES3?


I'm trying to understand when the Typescript compiler will transpile code to make it compatible with my specified target ECMAScript version (ES5 or ES3).

For example, TSC will transpile for(var int of intArray) fine, but it doesn't transpile Number.isInteger() (which is an ES6 feature, according to w3schools).

Number.isInteger() isn't supported in IE < 11.0, so this is a problem. Visual Studio (and VS Code) don't provide warnings of incompatibility, and it doesn't get transpiled.

What can I expect to get transpiled, and what won't? I initially expected that everything would be transpiled, so that I wouldn't have to keep track of things like this, but that doesn't seem to be the case.


Solution

  • TypeScript transpiles but does not polyfill. So one way to think of it is that anything that is not valid syntax in your target will be transpiled to a valid syntax. For example, when using the class keyword with your target set to ES5, it will transpile this:

    class Greeter {
    }
    

    to this:

    var Greeter = /** @class */ (function () {
        function Greeter() {
        }
        return Greeter;
    }());
    

    (You can play around more with this here.)

    On the other hand, it does not add missing functionality, which you'll have to polyfill yourself. Number.isInteger() is valid ES5 syntax, it's just not functionality that exists in ES5. You can polyfill this yourself by importing babel-polyfill (which uses core-js under the hood) or using a service like polyfill.io.

    Note: don't confuse the lib option with polyfills. This does not polyfill features. It simply tells TypeScript to act as if features from those ES versions are present, so it will type check them appropriately. You still need to handle the polyfill piece yourself for browsers that you support. If you don't specify the appropriate libs, TypeScript will complain that it doesn't know what Number.isInteger() represents.

    I'm not aware of a comprehensive list of which features TypeScript transpiles, but you can see a table for TypeScript+core-js polyfills here. More reading on polyfills vs transpilation here.