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
I am very impressed by the type inference TypeScript can do with switch and for...else statements.
I miss, however, type inference for map object lookups.
Code
typeNamed={kind: "named",id: string};typeDecimal={kind: "decimal",id: number};typeHex={kind: "hex",id: number};typeEntity=Named|Decimal|Hex;letareaFunctions={"named": function(s: Named){return"&"+s.id+";";},"decimal": function(s: Decimal){return"&#"+s.id+";";},"hex": function(s: Hex){return"&#x"+s.id+";";},"something else": {}}// worksletprintEntity1=function(s: Entity){switch(s.kind){case"named": returnareaFunctions["named"](s);// This works perfectly, TS knows that s can only be to type 'named', here// It also knows the function definition and sees that both matchcase"decimal": returnareaFunctions["decimal"](s);case"hex": returnareaFunctions["hex"](s);}}// does not workletprintEntity2=function(s: Entity){returnareaFunctions[s.kind](s);// error, although it is equivalent to printEntity1}// does not work, although a common JS patternletprintEntity3=function(s: Entity){if(areaFunctions[s.kind]){returnareaFunctions[s.kind](s);// type inference does not work}return"-";}
Expected behavior:
printEntity2 would compile
Actual behavior:
But it doesn't. I am forced to expand a single line into a long switch statement (just 3 lines here, but a lot more -- and often used -- in my project).
The text was updated successfully, but these errors were encountered:
There are multiple features that are not supported today that contribute to blocking this scenario.. first, The main is that a union property is not callable unless all variants have the same signature. so we would need #7294 first to be able to address this issue. Second we will need to distribute the union over the whole call expression, i,.e. the type of areaFunctions[s.kind](s) would be typeof areaFunctions["named"](s) | tyoeof areaFunctions["decimal"](s) | | tyoeof areaFunctions["hex"](s); then we will need to do some narrowing on s in each branch based on the type of s.kind.
#7294 is the main issue, we currentlly have now way of resolving a union call.
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
TypeScript Version: 2.6.1
Description
I am very impressed by the type inference TypeScript can do with
switch
andfor...else
statements.I miss, however, type inference for map object lookups.
Code
Expected behavior:
printEntity2 would compile
Actual behavior:
But it doesn't. I am forced to expand a single line into a long switch statement (just 3 lines here, but a lot more -- and often used -- in my project).
The text was updated successfully, but these errors were encountered: