You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To be illustrative of the issue, imagine a toy class:
classTest{something(x: number): number;something(x: string): string;something(x: number|string){if(typeofx==="number"){returnx*2;}else{returnx+' 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(typeofx==="number"){returnx*2;}else{returnx+' 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(typeofx==="number"){returnx*2;}else{returnx+' 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.
The text was updated successfully, but these errors were encountered:
var foo : (x: number) => number;
var bar : (x: number | string) => number | string;
foo = bar; // Error number | string is not assignable to number
bar = foo; // Ok. number is assginable to number | string.
/*
A union type U is assignable to a type T if each type in U is assignable to T.
A type T is assignable to a union type U if T is assignable to any type in U.
*/
DanielRosenwasser
changed the title
Poor type safety with function overloads and their implementation
Overload/implementation compatibility forces users to use default to 'any' return type
Oct 21, 2015
To be illustrative of the issue, imagine a toy class:
This will not compile, since it is unable to find the best common type between 'number' and 'string'. If modified like this:
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:
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:
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.The text was updated successfully, but these errors were encountered: