Description
Search Terms
discriminated union, hashmap, switch, object, map, router
Suggestion
When a hashmap object property is accessed by a union discriminant, check if the resulting property covaries with the discriminant in a compatible way.
Example
interface UnionComponentA { discriminant: "A", foo: number }
interface UnionComponentB { discriminant: "B", bar: boolean }
interface UnionComponentC { discriminant: "C", baz: string }
type Union = UnionComponentA | UnionComponentB | UnionComponentC
const handleA = (arg: UnionComponentA) => console.log(arg.foo)
const handleB = (arg: UnionComponentB) => console.log(arg.bar)
const handleC = (arg: UnionComponentC) => console.log(arg.baz)
const router = {
A: handleA,
B: handleB,
C: handleC
};
function route(union: Union){
router[union.discriminant](union) // <--- !
}
Currently: the line with <--- !
comment would incur a type error, since union
cannot fit into the intersection of UnionComponentA & UnionComponentB & UnionComponentC
, which is the safe way of making sure that union
can be accepted by any property of router
.
Wanted: in reality, we could infer that the type of union
is discriminated in way that it will always match the call signature that is the result of indexing route
. This inference (I guess) would require that the indexed route
function property is invoked immediately with the discriminated union as argument.
Use Cases
This can, in some cases, be much more concise than a long switch. This is especially true if handle*
functions above accept multiple arguments, and only one is polymorphic that would currently require use of switch
to resolve:
switch (union.discriminant){
case "A":
handleA(some, long, arglist, before, the, discriminated, union) // the last position is polymorphic
break
case "B":
// ... same deal ...
}
Disclaimer: I don't know if this kind of reasoning is too "niche", and maybe somebody more knowledgeable than me with TypeScript's internal can generalize what I'm asking for here or present an existing pattern that fulfill the spirit of what this suggestion would achieve. Another case that would employ a similar kind of inference might be something like assigning a discriminated union to a specific, compatible property of route
; but I don't see a practical use case of this.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code <-- (Um, I believe it doesn't, but more knowledgeable people can maybe correct me!)
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals. <--- I think it does..., again would welcome any explanation otherwise!