TypeScript Version: 2.6.1
Description
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
type Named = { kind: "named", id: string };
type Decimal = { kind: "decimal", id: number };
type Hex = { kind: "hex", id: number };
type Entity = Named | Decimal | Hex;
let areaFunctions = {
"named": function (s: Named) { return "&"+s.id+";"; },
"decimal": function (s: Decimal) { return "&#"+s.id+";"; },
"hex": function (s: Hex) { return "&#x"+s.id+";"; },
"something else": {}
}
// works
let printEntity1 = function (s: Entity) {
switch (s.kind) {
case "named": return areaFunctions["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 match
case "decimal": return areaFunctions["decimal"](s);
case "hex": return areaFunctions["hex"](s);
}
}
// does not work
let printEntity2 = function (s: Entity) {
return areaFunctions[s.kind](s); // error, although it is equivalent to printEntity1
}
// does not work, although a common JS pattern
let printEntity3 = function (s: Entity) {
if (areaFunctions[s.kind]) {
return areaFunctions[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).
TypeScript Version: 2.6.1
Description
I am very impressed by the type inference TypeScript can do with
switchandfor...elsestatements.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).