I'm trying to understand how function overloading in typescript works.
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');
}
The code above throws the error:
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 ensured that I resolve the parameter tag
before returning the appropriate type for a given tag
type. Any ideas why this doesn't work?