问题
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;
};
}
回答1:
You need to declare it in the global
namespace:
declare global {
interface Array<T> {
includes(searchElement: T) : boolean;
}
}
More
Extending lib.d.ts is covered here : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html 🌹
回答2:
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';
来源:https://stackoverflow.com/questions/37640785/how-do-you-add-polyfills-to-globals-in-typescript-modules