Typescript,'NodeListOf<Element>' 不是数组类型也不是字符串类型

Typescript,'NodeListOf<Element>' is not an array type or a string type

正在将我的 JS 转换为 TS 严格模式。

以下语法对我来说看起来不错,但 TS 在 allSubMenus 上的 for 循环中抱怨:

[ts] Type 'NodeListOf<Element>' is not an array type or a string type.

我错过了什么?

function subAct(target:Node){

  const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 

  for (const sub of allSubMenus){
    sub.classList.remove('active')
  }  
}

您需要将 target 编译器选项设置为 es6 或更高才能使 NodeListOf<T> 可迭代。

根据您的 typescript 目标编译器,可能会发生解析错误。

我对 HTMLCollectionOf 有同样的问题

要解决这个问题,

  1. 您可以像@Matt McCutchen 提到的那样更改您的 TS 目标编译器
  2. 使其成为任何语法

const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 

for (const sub of allSubMenus as any){ // then will pass compiler
  sub.classList.remove('active')
}  

注意:声明“any”会使 collection(Objects) 只是数组,这会影响某些打字稿功能。


有关 ECMAScript(ES) 历史的更多信息,请查看以下 URL。 https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c

你可以试试

const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 
Array.from(allSubMenus, subMenu => {/* */})

您可以使用 forEach 方法迭代 NodeListOf

const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems') 
allSubMenus.forEach(sub => sub.classList.remove('active'))

来源:https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules_typedoc_node_modules_typescript_lib_lib_dom_d_.nodelistof.html#foreach

tsconfig.json 文件的 compilerOptions 中设置 "downlevelIteration": true

来自https://www.typescriptlang.org/tsconfig#downlevelIteration

Downleveling is TypeScript’s term for transpiling to an older version of JavaScript. This flag is to enable support for a more accurate implementation of how modern JavaScript iterates through new concepts in older JavaScript runtimes

编译代码时,您可以选择 target: ES2017target: ES2015。你也可以在 tsconfig.json 文件中设置这个 属性 unser compilerOptions.

所以这里是命令行代码:

npx tsc path/to/file.ts --target ES2015

提示: 如果您将 babel 与 typescript 一起使用,完全建议您始终将 typescript 编译为最新版本 Javascript,然后让 babel 处理其余的处理过程。使用这种技术,您可以为旧版浏览器添加另一个保证支持级别的杠杆,因为打字稿不能编译在例如 ie6 中 运行 的代码;所以 babel 来拯救这里,让你确保你的 js 代码甚至 运行 在 ie < 9 中,它有帮助的 polyfills 和其他工作所需的机制!

所以请记住:

始终让 typescript 将您的代码编译到最新的 javascript(通过设置 target: ES2017)并让 babel 转译您的 js 代码以支持较旧的浏览器(正确分离关注点并让每个关注点完成相关工作).