typescript linter 在尝试制作 polyfill 时触发错误

typescript linter triggers error when trying to make a polyfill

我正在尝试为我的应用程序制作一些适用于不同浏览器的 polyfill, 我有一个导入其他文件的文件,当我导入它时打字稿失败。

如果我注释掉 - import "../scripts/polyfill_es5" 一切正常,

如果我包含它,脚本会失败并显示 -

Property 'assignDeep' does not exist on type 'Object'

为什么我的导入会破坏代码?

这些是我的文件:

Polyfill.ts:

import "../scripts/polyfill_es5"

interface Object {
    assignDeep: (target: {}, ...sources: any[]) => object;
}

Object.prototype.assignDeep = (target: {}, ...sources: any[]) => { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
    }

    const to = Object(target);
    let nextSource;

    for (let index = 1; index < sources.length; index++) {
        nextSource = sources[index];

        if (nextSource != null) { // Skip over if undefined or null
            for (const nextKey in nextSource) {
                // Avoid bugs when hasOwnProperty is shadowed
                if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                    if (typeof to[nextKey] === 'object'
                        && to[nextKey]
                        && typeof nextSource[nextKey] === 'object'
                        && nextSource[nextKey]) {
                        to[nextKey] = Object.assignDeep(Array.isArray(to[nextKey]) ? [] : {}, to[nextKey], nextSource[nextKey]);
                    } else {
                        to[nextKey] = nextSource[nextKey];
                    }
                }
            }
        }
    }
    return to;
};

polyfill_es5.ts:

interface NodeList {
    forEach : (callback : (currentValue : Node, currentIndex : number, listObj : NodeList) => void, thisArg : string|Window) => void;
}

if (typeof NodeList !== 'undefined' && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = (callback : (currentValue : Node, currentIndex : number, listObj : NodeList) => void, thisArg : string|Window) => {
        thisArg = thisArg || window;
        for (let i = 0; i < this.length; i++) {
            callback.call(thisArg, this[i], i, this);
        }
    };
}

您需要进行全局增强:

declare global {
  interface Object {
    assignDeep: (target: {}, ...sources: any[]) => object;
  }
}

当文件包含顶级import/export 语句时,TypeScript 编译器会将文件视为模块文件。所以你的 interface Object { } 是文件本地的,而不是全局的 Object.