I want to make a function which will take an HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement and will derive a value based on its properties. The implementation seemed fairly simple to begin with:
function deriveValue(element: HTMLInputElement) {
switch (element.type) {
case 'number':
return element.valueAsNumber;
default:
return element.value;
}
}
Things started to get a bit weird here as my signature became:
function deriveValue(element: HTMLInputElement): string | number;
When I used it like so, it showed the value of t as being number | string
const element = document.createElement('input');
element.type = 'number';
deriveValue(element) // number | string
I reached to make an overload, but it didn't seem to work as I wanted:
function deriveValue(element: HTMLInputElement & { type: 'number' }): number;
function deriveValue(element: HTMLInputElement): string;
function deriveValue(element: HTMLInputElement) {
switch (element.type) {
case 'number':
return element.valueAsNumber;
default:
return element.value;
}
}
This still doesn't work. I think the problem might derive from type being defined as string on these elements
Is it possible to make overrides like this on top of an HTMLElement?