I'm currently exploring the concept of function overloading in TypeScript and how it functions.
type CreateElement = {
(tag: 'a'): HTMLAnchorElement
(tag: 'canvas'): HTMLCanvasElement
(tag: 'table'): HTMLTableElement
}
let createElement: CreateElement = (tag: 'a' | 'canvas' | 'table') => {
if (tag === 'a') return new HTMLAnchorElement()
if (tag === 'canvas') return new HTMLCanvasElement()
if (tag === 'table') return new HTMLTableElement()
throw new Error('wrong tag');
}
An issue arises from the code above:
Type 'HTMLAnchorElement | HTMLCanvasElement | HTMLTableElement' is not assignable to type 'HTMLAnchorElement'.
Type 'HTMLCanvasElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 21 more.
I have made sure that I properly handle the parameter tag
before returning the corresponding type based on the tag
. Can anyone provide insight into why this implementation is failing?