typescript 上的 document.querySelectorAll:类型“NodeListOf<HTMLElement>”不是数组 type.ts(2461)

Lhe*_*hew 4 dom typescript

我一直在尝试一种方法来在打字稿上获得以下内容:

    [...document.querySelectorAll<HTMLElement>("#node-a input, #node-a button")].forEach(item => {
//code
    })

Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Type 'NodeListOf<HTMLElement>' is not an array type.ts(2461)

这有什么问题吗?

小智 7

document.querySelectorAll返回 a NodeList,而不是数组。要将其视为数组,您可以Array.from()按照建议使用,或者更改代码以期望 NodeList。请注意,某些浏览器不支持forEach()与 NodeList 一起使用。