I recently developed a function to generate dynamic elements. However, I encountered an issue where instead of returning the precise type of the element, it was producing a union of various <HTMLElementTagNameMap>
types.
function createCustomElement(type: keyof HTMLElementTagNameMap) {
return document.createElement(type)
}
When using the function as is, it resulted in a Union of :
(HTMLElement | HTMLObjectElement | HTMLAnchorElement | HTMLAreaElement | HTMLAudioElement | ... and many more ... | HTMLVideoElement).
To address this issue, I attempted the following solution:
type valueOf<T> = T[keyof T]
function createCustomElement<T extends valueOf<HTMLElementTagNameMap>>(type: keyof HTMLElementTagNameMap) {
return document.createElement(type) as T
}
P.S. - I must admit, even I found this solution perplexing! How did it actually work?
Instead of utilizing the function as described above, I wanted to achieve automatic inference of the type for the parameter type
, similar to what happens with:
let newElement = document.createElement('new')