如何在打字稿(模块)中向Globals添加polyfill

Rom*_*her 7 shim polyfills typescript

我能够为Array#includes找到一个polyfill(堆栈溢出)并将其添加到typescript但是在我的文件中添加一个小的导入后它变成了一个模块(我明白他们为什么要这样做导出,但为什么要导入)我再也无法修改全局命名空间了.

如何修复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;
    };
}
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 11

您需要在global命名空间中声明它:

declare global {
  interface Array<T> {
      includes(searchElement: T) : boolean;
  }
}
Run Code Online (Sandbox Code Playgroud)

更多

扩展lib.d.ts包括在这里:https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html


Iva*_*nko 5

除了添加声明之外,您还需要在代码中包含此polyfill。一种方法是在应用程序的入口点模块中导入带有 poylfill 声明和实现的文件,只要您正在填充核心对象并希望它们在应用程序中的任何位置可用(假设您的 polyfill 位于./polyfill/arrayIncludes.ts)像这样:

import './polyfill/arrayIncludes';
Run Code Online (Sandbox Code Playgroud)