What is the array type for html elements in typescript?

11,756

You need to use NodeListOf<T>, for example:

let games : NodeListOf<Element> = document.getElementsByTagName("game");

You could use type assertions to force it into an HTMLElement[], but this would give misleading type information and make your tools lie.

Share:
11,756
Kokodoko
Author by

Kokodoko

Creative Technologist and Lecturer. I give workshops about building web apps, games and IoT devices with Typescript, Javascript, CSS, MakeCode, Arduino. Also dabbling in Machine Learning for the web.

Updated on July 25, 2022

Comments

  • Kokodoko
    Kokodoko almost 2 years

    I have a typescript variable that stores the result of a DOM query:

    let games = document.getElementsByTagname("game");
    

    But what is the correct type of the result array? I would expect an array that contains htmlelements?

    // not working
    let games : Array<HTMLElement> = document.getElementsByTagName("game");
    // also not working
    let games : NodeList<HTMLElement> = document.getElementsByTagName("game");
    
  • Kokodoko
    Kokodoko about 8 years
    Ah.. I didn't realise "NodeListOf" was actually a type... (what does the "Of" mean?). Also, why so many different types for DOM elements? (NodeList, NodeListOf, Element and HTMLElement). It seems a lot of hassle to keep casting from one type to another just to fetch a div from my DOM.
  • Gabriel Petersson
    Gabriel Petersson about 4 years
    the "Of" means what that it is a NodeList OF the type X, for example NodeListOf<HTMLElement> means a list of the node type HTMLElement. The reason you need to cast is that there are hundreds of node types that can be yielded by javascripts querySelectors or other selectors, and in typescript you want to be certain to throw an error if wrong node type is yielded..