My code:
var checkboxes = this.element.querySelectorAll(\"input[type=checkbox]\") as NodeListOf;
checkboxes.forEach(ele =>
Honestly you could convert a NodeListOf to an array so that typescript will not complain about nodelist.forEach, but this is only solving the problem by adding unnecessary code. You can tell typescript to understand the native nodelist.forEach syntax by adding the dom.iterable library to your tsconfig.json. Here is an example of one of my tsconfig.json files.
{
"compilerOptions": {
"outDir": "./public/js/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"allowJs": true,
"moduleResolution": "node",
"rootDir": "src",
"lib": [
"es6",
"dom",
"dom.iterable"
],
"typeRoots": [
"node_modules/@types"
],
"removeComments": false
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"public",
"**/*.spec.ts"
]
}
Not all browsers support nodelist.forEach so I would definitely polyfill it https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
There is no guarantee forEach
will exist on this type - it can, but not necessarily (e.g. in PhantomJS and IE), so TypeScript disallows it by default. In order to iterate over it you can use:
1) Array.from():
Array.from(checkboxes).forEach((el) => { /* do something */});
2) for-in:
for (let i in checkboxes) {
if (checkboxes.hasOwnProperty(i)) {
console.log(checkboxes[i]);
}
}