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

倾然丶 夕夏残阳落幕 提交于 2019-12-04 03:16:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!