Typescript,'NodeListOf<Element>' is not an array type or a string type
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,
- you can change your TS target compiler as @Matt McCutchen mentioned OR
- 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'))
Sam
Updated on December 15, 2021Comments
-
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 onallSubMenus
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') } }