How do you add polyfills to Globals in typescript (modules)

Roman A. Taycher picture Roman A. Taycher · Jun 5, 2016 · Viewed 11.5k times · Source

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;
    };
}

Answer

basarat picture basarat · Jun 6, 2016

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 🌹