One of the benefits of TypeScript is its ability to leverage new features from ES6 and convert them to ES5; however, it does not automatically provide polyfills for built-in functions that are exclusive to ES6 and not available in ES5.
If you are utilizing these ES6-specific functions while targeting an ES5 environment, you will need to incorporate the necessary polyfills to ensure compatibility.
Case in point
Take the fill
function which is newly introduced in ES6 as a method on the prototype of Array
.
const result = ["first", "second"].fill("all");
This code will run smoothly when compiling for ES6 because TypeScript assumes the presence of the fill
function in ES6 environments by including lib.es6.d.ts.
However, when targeting ES5, TypeScript will raise an error indicating the absence of the fill
function:
error TS2399: Property 'fill' does not exist on type 'string[]'.
To rectify this issue, you must manually extend the Array<T>
interface with the definition for fill
in your project:
interface Array<T> {
fill(value: T, start?: number, end?: number): this;
}
Additionally, you should include a polyfill or utilize tools that automate this process.