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

时间:2018-01-08 06:59:33

标签: javascript typescript webpack tslint

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

如果我发表评论- import "../scripts/polyfill_es5" 一切正常,

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

  

属性'assignDep'在'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);
        }
    };
}

1 个答案:

答案 0 :(得分:2)

您需要进行全局扩充:

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

当文件包含顶级导入/导出语句时,TypeScript编译器会将该文件视为模块文件。因此,您的interface Object { }是文件的本地,而不是全局Object