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

你。 提交于 2020-07-18 03:36:30

问题


Converting my JS to TS strict mode.

The following syntax looks fine to me but TS is complaining in the for loop on allSubMenus with:

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

What am I missing?

function subAct(target:Node){

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

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

回答1:


You need to set the target compiler option to es6 or higher for NodeListOf<T> to be iterable.




回答2:


This is typescript side parse error. I had same problem with HTMLCollectionOf

make it as any, it works for me

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

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



回答3:


You could try

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



回答4:


You can iterate over a NodeListOf with the forEach method.

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

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



来源:https://stackoverflow.com/questions/51723962/typescript-nodelistofelement-is-not-an-array-type-or-a-string-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!