TypeScript is very particular about what is and isn't allowed in a TS file to protect you from common developer errors. By default if you set the compile target to ES5 it only allows you to use globally defined variables that were available in the ES5 time-frame. That said it is super easy to configure TypeScript to use ES6 or ESNext using the
We also cover how to make sure that these features work across the widest range of browsers using a simple polyfill.
Now, let's go ahead and create an index file within our source folder. Because we specified the compiler option target to be ES5, TypeScript will happily allow us to use ES5 features, for example, the map function from array prototype.
The main effect of specifying target ES5 in the compiler options is that if you try to use any ES6 syntax, TypeScript will go ahead and transpile to an ES5 syntax. For example, if you have an error function that returns null, TypeScript will go ahead and transpile it into a simple function that does the same thing.
The side effect of using the ES5 target is that we are not allowed to use the runtime features that are available in common ES5 environments. For example, if you try to use a promise, TypeScript complains, "Cannot find the name promise."
This is an example of TypeScript protecting us from writing code that will not work in an ES5 environment. We can still keep our target as ES5, but tell TypeScript to allow runtime for the environments using the lib option in our tsconfig.json.
Here, we tell TypeScript to include the standard DOM environment, and allow all runtime features that are available up until ES6. As soon as you do that, you can now see that TypeScript no longer complains if you try to use ES6 features, such as promises.
If you are building an NPM package, this will be OK. However, if you are targeting browsers, that is building an application instead of a library, you might also want to polyfill these new features like promise, map, set, etc.
The simplest way to do it is to simply install the polyfill called Core.js. We can install it easily using NPM, by running the command npm install core-js, and receive it our devDependencies.
Once it is installed, you simply include it in your application by importing Core.js/shim into your main module to make sure that all the latest ES features are available when the application is used by all browsers.
Here, you can see that promise is safe to use for non-obsolete platforms, using TypeScript with Core.js.