Closed Nevor closed 9 years ago
I gave a talk yesterday pointing this very example, among others, as future work. :)
@avikchaudhuri do you have a link to said talk ?
Is this any different from #20? If not, can we close this in favor of that issue to keep the conversation in one place?
Merging with #20.
As OCaml programmers, you know that tagged unions are very useful a wide range of situation and it might be interesting to encode them in Javascript in a safe way (i.e. type checked by Flow).
Current workaround and motivating example
One way of encoding them is to create a union type of disjoint types, the usual way is to use a tag property that will defer for each "constructor". You already encode them that way in your flux-chat example :
Definitions :
Destruction :
Unfortunately, in these example, you are using the
any
type for tag and payload. The construction and destruction is not safe, anything is usable as a tag and anything can go through a switch case.A quick safe solution is to use some kind of singleton type as a tag (for instance a string literal type) and to extend type guards to the switch statement and to narrow union types.
Previous proposal in Typescript
This very situation is also a problem we spotted in Typescript too. Leveraging the recent addition of type aliases and union type, we have made a same proposal to Typescript developers. https://github.com/Microsoft/TypeScript/issues/1003. Furthermore, we have developed a prototype Typescript extended to handle string literal types in implementation files and extended
if
andswtich
guards.In our implementation, your chat example would roughly become :
The construction and destruction of the tagged union are then type checked for a safer usage.
Any plan in Flow
The string literal types (albeit not documented) and simple type guards are already available and working as expected in Flow. The question is whether you are planning to go toward this direction in term extended type guards or safe tagged union (in any chosen encoding).
As a side note, we are willing to contribute if it's acceptable but not planned.