I was able to find a polyfill(on stack overflow) for Array#includes and add it to typescript but after adding a small import to my file it turned into a module(I understand why they do this for export, but why on import) and I couldn't modify the global namespace anymore.
How do I fix the polyfill?
interface Array<T> {
includes(searchElement: T) : boolean;
}
// Add Array includes polyfill if needed
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
declare global is used inside a file that has import or export to declare things in the global scope. This is necessary in files that contain import or export since such files are considered modules, and anything declared in a module is in the module scope.
The TypeScript declares module is one of the modules and keyword it is used for to surround and define the classes, interfaces; variables are also declared it will not originate with the TypeScript like that module is the set of files that contains values, classes, functions/methods, keywords, enum all these contains ...
You need to declare it in the global
namespace:
declare global {
interface Array<T> {
includes(searchElement: T) : boolean;
}
}
Extending lib.d.ts is covered here : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html 🌹
Besides adding a declaration, you need to include this polyfill in your code. One way to do that is by importing the file with poylfill declaration and implementation in the entry point module of your application as long as you're polyfilling core objects and want them to be available anywhere in your app (assuming you have your polyfills in ./polyfill/arrayIncludes.ts
) like this:
import './polyfill/arrayIncludes';
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