Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')   }   } 
like image 885
Sam Avatar asked Aug 07 '18 09:08

Sam


Video Answer


2 Answers

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

like image 166
Matt McCutchen Avatar answered Sep 26 '22 00:09

Matt McCutchen


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

like image 26
John Avatar answered Sep 25 '22 00:09

John