Looking for the most effective method to define HTML elements in typescript is a challenge I am facing. One particular issue that keeps arising is when dealing with arrays of DOM nodes retrieved using document.querySelectorAll
. The type assigned to these elements is often Element
, which causes problems when trying to set the style attribute.
If I attempt to set the type as Element
and then modify the style, an error message pops up:
Property 'style' does not exist on type 'Element'.
But if I change the type to HTMLElement
, another error occurs:
Argument of type 'Element' is not assignable to parameter of type 'HTMLElement'. Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 111 more.
To illustrate this problem, here's a simple example code snippet:
type El = HTMLElement
const boxes = document.querySelectorAll('.box')
const setStyle = (el: El) => {
el.style.background = 'green'
}
boxes.forEach(box => {
setStyle(box)
})
The question now becomes - what is the correct approach to address this issue? One workaround would be to use explicit casting like so:
boxes.forEach(box => {
setStyle(box as HTMLElement)
})
However, having to constantly rely on this workaround may seem counterproductive. Is there a better way to handle this situation?