After exploring TypeScript, I encountered an issue while creating a shorthand for querySelectorAll()
export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null {
return [...parent.querySelectorAll(DOMElement)];
}
The code above resulted in an error saying
Type 'Element[]' is not assignable to type 'HTMLElement[]'
.
So, I made a slight modification to my code
export function selectAll(DOMElement: string, parent = document): Array<HTMLElement> | null {
return Array.from(parent.querySelectorAll(DOMElement));
}
This change resolved the error. This led me to two questions:
- Why did
Array<HTMLElement>
not work butArray<Element>
worked? - Which method should I use - spread operator
[...]
orArray.from()
?
Additionally
As mentioned by bogdanoff in a comment
"from docs querySelectorAll
returns a non-live NodeList containing Element
so Array<Element>
is right type."
If that's the case, why does querySelector
have no issues returning HTMLElement
instead of just Element
?
export function selectAll(DOMElement: string, parent = document): HTMLElement | null {
return parent.querySelector(DOMElement);
}