为什么NodeListOf上不存在forEach

时间:2017-11-26 02:56:46

标签: javascript typescript

我的代码:

    var checkboxes = this.element.querySelectorAll("input[type=checkbox]") as NodeListOf<HTMLInputElement>;
    checkboxes.forEach(ele => {
        var key = ele.name;
        if (data.hasOwnProperty(key)) {
            if (!this.isArray(data[key])) {
                var temp = data[key];
                data[key] = [temp];
            }
        } else {
            data[key] = [];
        }
    });

但我收到了一个错误:

  

错误TS2339:属性'forEach'在类型上不存在   'NodeListOf'。

interface NodeListOf<TNode extends Node> extends NodeList {
    length: number;
    item(index: number): TNode;
    [index: number]: TNode;
}

interface NodeList {
    /**
     * Returns an array of key, value pairs for every entry in the list
     */
    entries(): IterableIterator<[number, Node]>;
    /**
     * Performs the specified action for each node in an list.
     * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.
     * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void;
    /**
     * Returns an list of keys in the list
     */
    keys(): IterableIterator<number>;

    /**
     * Returns an list of values in the list
     */
    values(): IterableIterator<Node>;


    [Symbol.iterator](): IterableIterator<Node>;
}
'NodeListOf'继承自'NodeList','NodeList'拥有'forEach'  方法,'NodeListOf'上不存在'forEach'的原因?

2 个答案:

答案 0 :(得分:20)

此类型不存在保证forEach - 它可以但不一定(例如在PhantomJS和IE中),因此TypeScript默认情况下不允许它。为了迭代它,您可以使用:

1)Array.from():

Array.from(checkboxes).forEach((el) => { /* do something */});

2)for-in:

for (let i in checkboxes) {
  if (checkboxes.hasOwnProperty(i)) {
    console.log(checkboxes[i]);
  }
}

答案 1 :(得分:9)

老实说,可以将NodeListOf转换为数组,这样打字稿就不会抱怨 nodelist .forEach,但这只是通过添加不必要的代码来解决问题。您可以通过将 dom.iterable 库添加到tsconfig.json来告诉typescript了解本机 nodelist .forEach语法。这是我的一个tsconfig.json文件的示例。

{
  "compilerOptions": {
  "outDir": "./public/js/",
  "noImplicitAny": true,
  "module": "es6",
  "target": "es5",
  "allowJs": true,
  "moduleResolution": "node",
  "rootDir": "src",
  "lib": [
    "es6",
    "dom",
    "dom.iterable"
  ],
  "typeRoots": [
    "node_modules/@types"
  ],
  "removeComments": false
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "public",
    "**/*.spec.ts"
  ]
}

并非所有浏览器都支持 nodelist .forEach所以我肯定会将其填充https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach