属性NodeListOf上不存在属性forEach

Ghe*_*man 29 typescript angular

Angular 2.4.4,TypeScript 2.1.5,PhpStorm 2017.2.1我写这段代码:

const list = document.querySelectorAll('path.frame-zone');
list.forEach(() => {
Run Code Online (Sandbox Code Playgroud)

但是,第二行强调用红色线及TsLint报告说,"财产的forEach不上型NodeListOf存在"但是,当我按Ctrl +单击forEach它得到我lib.es6.d.ts在那里forEach被宣布为interface NodeListOf<TNode extends Node>

为什么它不会让我使用它?怎么了?

Der*_*rek 61

您需要将其转换为数组:

const frameZones = Array.from(document.querySelectorAll('path.frame-zone'));
frameZones.forEach((...) => {});
Run Code Online (Sandbox Code Playgroud)

  • 实际上,使用 ES6,您可以更轻松地实现此目的: `const frameZones = [...document.querySelectorAll('path.frame-zone')];` 干杯! (3认同)

tib*_*alt 20

只需添加"dom.iterable"tsconfig.json,所以它看起来有点像这样:

{
    "compilerOptions": {
        "lib": [
            "es6",
            "dom",
            "dom.iterable"
        ],
...
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案.谢谢! (2认同)

Buk*_*ksy 7

您可以对其进行强制转换,以使编译器知道可以对其进行迭代:

(document.querySelectorAll('path.frame-zone') as any as Array<HTMLElement>).forEach();
Run Code Online (Sandbox Code Playgroud)