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

22,356

Solution 1

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

Solution 2

According to your typescript target compiler, parsing error can be occured.

I had same problem with HTMLCollectionOf<Element>

To solve this issue,

  1. you can change your TS target compiler as @Matt McCutchen mentioned OR
  2. make it as any syntax

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

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

Note: Declaring "any" makes collection(Objects) as just array and this will affect some typescript features.


For more information about ECMAScript(ES) history, please have a look the following URL. https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c

Solution 3

You could try

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

Solution 4

Set "downlevelIteration": true in compilerOptions in your tsconfig.json file.

From 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

Solution 5

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

Share:
22,356
Sam
Author by

Sam

Updated on December 15, 2021

Comments

  • Sam
    Sam over 2 years

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