Type 'HTMLCollectionOf<HTMLCanvasElement>' must have a '[Symbol.iterator]()' method that returns an iterator Type 'HTMLCollectionOf<HTMLCanvasElement>' must have a '[Symbol.iterator]()' method that returns an iterator typescript typescript

Type 'HTMLCollectionOf<HTMLCanvasElement>' must have a '[Symbol.iterator]()' method that returns an iterator


In order to iterate that way you need to set compilerOptions like this:

"compilerOptions": {        // ...        "target": "ES6",        "lib": [            "DOM",            "DOM.Iterable",            "ES6"        ]        // ...    }


I've got this in my tsconfig.json:

"compilerOptions": {  // ...  "target": "es2015",  "module": "es2020",  "lib": [    "es2018",    "dom"  ]  // ...}

I add dom.Iterable to lib and output is gone. Now it look like this:

"compilerOptions": {  // ...  "target": "es2015",  "module": "es2020",  "lib": [    "es2018",    "dom",    "dom.Iterable"  ]  // ...}


It may be worth checking your TypeScript / definitions version, because I get no errors. I believe the errors relate to some older browsers actually not supporting iteration of the HTML collection, so you could use a traditional for loop.

Both examples shown below:

const myCanvas: HTMLCollectionOf<HTMLCanvasElement> = document.getElementsByTagName('canvas');for (const image of myCanvas) {  console.log(image.toDataURL());}for (let i = 0; i < myCanvas.length; i++) {  console.log(myCanvas[i].toDataURL());}