According to your typescript target compiler, parsing error can be occured.
The for-of loop, introduced in the sixth edition of EcmaScript (ES6). Thus, old browsers' JS engine can not understand for-of loop syntax.
https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
To solve this issue,
if you support latest modern browsers(>=ES6) only
change your TS target
//tsconfig.json
{
"compilerOptions": {
"target": "es6" //above es6 like ES2015,ES2018 ...
}
}
if you support old browsers(<=ES5)
I presume that you are using next environment.
//.tsconfig.json
{
"compilerOptions": {
"target": "es5"
}
}
- To keep for-of loop, use as any syntax
Note: "as any" will cast collection(Objects) to array and this will affect some type features within "for" scope.
//.ts
const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems')
for (const sub of allSubMenus as any){ // then will pass compiler
sub.classList.remove('active')
}
The above TS script will be compiled to
//.js output
var allSubMenus = document.querySelectorAll('.subMenuItems');
for (var _a = 0, _b = forms; _a < _b.length; _a++) {
var sub = _b[_a];
sub.classList.remove('active');
}
https://stackblitz.com/edit/node-ywn1bq?file=main.js
- Use classic for-loop syntax
const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems')
for (let i = 0; i < allSubMenus.length; i++) {
allSubMenus[i].classList.remove('active');
}
<Element>
In addition to the above, to avoid the following warning,
Property '<property name>' does not exist on type 'Element'
you may specify <Element> if you know element type and type define exists.
//for example,
NodeListOf<Element> => NodeListOf<HTMLFormElement>
ECMAScript(ES) history
https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c
for (let i = 0; i < allSubMenus.length; i++) { allSubMenus[i].classList.remove('active'); }
– Dogbane