Alan Rezende

TypeScript Error – Type NodeListOf<Element> must have a Symbol.iterator() method that returns an iterator

  April 12, 2023
Updated on April 18, 2023
  April 12, 2023
Updated on April 18, 2023

Related to:: TypeScript

main.ts:3 ⛔️ error TS2488: Type 'NodeListOf<Element>' must have a '[Symbol.iterator]()' method that returns an iterator. 

To illustrate the error, consider the following code from my Obsidian Plugin:

let pre = document.querySelectorAll("pre:not(.frontmatter)");
val.plugins.commandLine.resizeElements(
    [...pre].filter(i => i.classList.contains('command-line'))
);

In this code, the val.plugins.commandLine.resizeElements function is used to resize an array of elements that have the class command-line. However, the error is thrown when attempting to iterate over the querySelectorAll response.

Solution

To solve this problem, simply add "DOM.Iterable" to your lib property on tsconfig.json as shown below:

{
  "compilerOptions": {
    "baseUrl": ".",
    "inlineSourceMap": true,
    "inlineSources": true,
    "module": "ESNext",
    "target": "ES6",
    "allowJs": true,
    "noImplicitAny": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "isolatedModules": true,
    "strictNullChecks": true,
    "lib": [
      "DOM",
      "DOM.Iterable",
      "ES5",
      "ES6",
      "ES7"
    ]
  },
  "include": [
    "**/*.ts"
  ]
}

In tsconfig.json, the lib property specifies the set of library files that are available to the TypeScript compiler. By adding "DOM.Iterable" to this property, the necessary Type Declarations are made available to fix the error.“

References