Let's say I want to use Object.values(). In order to use this, I have to set "lib":["es2017"]. But then I have "target":"es6".
The way I read this is that I am writing with es2017 methods and it's outputting es6 code.
So why do I need a polyfill, and how do I select a reliable one?
TypeScript distinguishes between API calls and syntax.
The TypeScript compiler levels down the syntax (recognizable by special characters like =>, ?, `, # and keywords like class or static) but not the API. To polyfill API calls, such as Array.prototype.flat (introduced in ES2019), you would need an extra compiler like Babel.
The following compiler config will convert the nullish coalescing operator (??) and the class itself but not the API call to Array.prototype.flat (although it is not present in ES5):
tsconfig.json
{
"compilerOptions": {
"lib": ["ES2019"],
"target": "ES5"
}
}
main.ts
export class MyConverter {
static flatten(numbers?: (number | number[])[]) {
return (numbers ?? []).flat();
}
}
main.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MyConverter = void 0;
var MyConverter = /** @class */ (function () {
function MyConverter() {
}
MyConverter.flatten = function (numbers) {
return (numbers !== null && numbers !== void 0 ? numbers : []).flat();
};
return MyConverter;
}());
exports.MyConverter = MyConverter;
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