I have been playing with TypeScript and I ran into a problem I wrote a shorthand for querySelectorAll()
export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null {
return [...parent.querySelectorAll(DOMElement)];
}
The above code giving me Type 'Element[]' is not assignable to type 'HTMLElement[]'.
Then I changed my code a little bit
export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null {
return Array.from(parent.querySelectorAll(DOMElement));
}
Now I am not getting any error. So, my questions are -
- Why
Array<HTMLElement>didn't work butArray<Element>worked. - What should I use
[...]spread operator orArray.from().
In Addition
Like bogdanoff mentioned in comment
"from docs querySelectorAll returns a non-live NodeList containing Element so Array<Element> is right type."
Then why querySelector is okay with returning HTMLElement instead of just Element
export function selectAll(DOMElement: string, parent = document): HTMLElement | null {
return parent.querySelector(DOMElement);
}
NodeListcontainingElementsoArray<Element>is right type.{...}refers to object spread and not array spread which would maybe be better rendered as[...].