Search code examples
typescriptselectors-apispread-syntax

In Typescript how can I set types for querySelectorAll with the spread syntax


I have this code.

const elements = [...document.querySelectorAll('.someClass')]

Combination of:

  • querySelectorAll
  • the spread operator

I can't figure out how to add Typescript types to this line.

I get errors from the console:

TS2548: Type 'NodeListOf<Element>' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator.

Solution

  • When you target es5 it doesn't work since TypeScript doesn't support filling in / polyfiling for Symbol.iterator

    If you target es6 it will work.

    Alternatively you can use Array.from using the lib option:

    const elements = [...Array.from(document.querySelectorAll('.someClass'))]
    

    Or more simply:

    const elements = Array.from(document.querySelectorAll('.someClass'))