Description
To be illustrative of the issue, imagine a toy class:
class Test {
something(x: number): number;
something(x: string): string;
something(x: number | string) {
if (typeof x === "number") {
return x * 2;
} else {
return x + ' is a string';
}
}
}
This will not compile, since it is unable to find the best common type between 'number' and 'string'. If modified like this:
something(x: number | string): number | string {
if (typeof x === "number") {
return x * 2;
} else {
return x + ' is a string';
}
}
then the earlier defined overload fails, saying it is not compatible with the signature of the implementation function.
The only way it seems like you can get this to compile is by simply defining it as any:
something(x: number | string): any {
if (typeof x === "number") {
return x * 2;
} else {
return x + ' is a string';
}
}
This now compiles, but now we have lost any benefit from being in the typescript world, since my implementation could just as easily do this:
something(x: number | string): any {
return { some: 'object' };
}
Is there a way around this or some solution I'm not seeing?
Note: I am aware that this can be typed without overloads at all, using union types, but this does not really satisfy to me, since the calling code will have to do typeof
checks or a typecast.