【问题标题】:How do you add polyfills to Globals in typescript (modules)如何在打字稿(模块)中向 Globals 添加 polyfill
【发布时间】:2016-06-05 10:19:21
【问题描述】:

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

如何修复 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;
    };
}

【问题讨论】:

    标签: typescript polyfills shim


    【解决方案1】:

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

    declare global {
      interface Array<T> {
          includes(searchElement: T) : boolean;
      }
    }
    

    更多

    这里介绍了扩展 lib.d.ts:https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html?

    【讨论】:

      【解决方案2】:

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

      import './polyfill/arrayIncludes';
      

      【讨论】:

      • 其他方法是什么?
      猜你喜欢
      • 2016-04-11
      • 2017-06-27
      • 2016-07-04
      • 1970-01-01
      • 2021-09-19
      • 2019-04-23
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多