I hope it is okay to post ReScript help requests here, but please direct me to a more appropriate place if this forum is just about ReScript roadmap etc.
I’m coming from the JS/TS world and I cannot for the life of me figure out how to have a function that can return different types. Here’s a playground link: https://reasonml.github.io/en/try?rrjsx=false&reason=C4TwDgpgBAbhBOAjA9gZwgeQK7DDqAvFAN4BQUsAhgDYCWAJgFxQrLUA05UAthKqpQDmEZqmDxaAO0GcAvgG5SpahGBQIAD0rcwKwlwoAKAH4BjABYRTAawTsox4OamCAKsgDClm-eMwaDACyfALCvlL+dPTB-EIQvpQAQshszKzUAJSEAHwkXCpqtKgAagH0hFAWVrbwhk4u7l7VGYpcSSnUUAD8BiSRDMxFpVH2vLHCgyVl3VRRMaHQg5L90SFxslCMvUNligqkQA
I would very much appreciate some help.
AFAIK it’s ok to ask questions in this forum.
Unlike js/ts/flow in ReScript/Reason your function can just return a single type,
in such cases like you mentiond above, you have to use a variant.
I have updated your example using a variant.
Variant is powerful feature of rescript’s type system, read more about them on rescript docs.
Feel free to ask questions
Thanks! And thanks for the updated playground; it’s really useful to have these examples to work from.
I would add to this, that you will probably be interested in an
@unboxed type, as that combines the best of both worlds. Type safety at compile time but no additional cost at runtime.
See this article for reference
Patrick has also written an interesting article on the topic:
And last but certainly not least, there is the
option as described by Yawar Amin here: