12

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;
    };
}
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141

2 Answers2

16

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.gitbook.io/typescript/type-system/lib.d.ts

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
basarat
  • 261,912
  • 58
  • 460
  • 511
5

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';
Ivan Leonenko
  • 2,363
  • 2
  • 27
  • 37