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

Sam picture Sam · Aug 7, 2018 · Viewed 14.8k times · Source

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')
  }  
}

Answer

John picture John · Nov 7, 2018

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')
  }