I am trying to teach students the intricacies of things like polymorphism via (in this case built-in) operator overloading, and I created an example I thought should work but didn't. I would love some insight from Typescript experts as to why this example fails.
function add2(a: number) {
return a + 2;
} // works fine, adds 2 and returns a number
function concat2(a:string) {
return a + 2;
} // works fine, concatenates '2' and returns a string
function addOrConcatenateTwo(a: string | number) {
return a + 2;
}
// compile error. I THOUGHT it would return a string | number but it errors out no matter what.
I thought that Typescript would see that + is defined for strings and + is also defined for numbers and it would allow the last function to run. That's how it works for shared method names across interfaces, so why does the + operator work differently?
This works fine and does exactly what I thought my example above would do. Is this a bug? Admittedly, one that would likely only appear in artificial educational scenarios?
function addOrConcatenateTwo(a: string | number) {
if (typeof (a) == "string") {
return a + 2;
} else {
return a + 2;
}
}
string | numberlike in above case. Instead it is suggested to e.g. use function overloads