Is there a simple short hand way to easily convert a simple variant to strings without the need to match on every variant?
type currency =
| USD
| CAD
| EUR
Looking to easily add
toString(currency) => string
Thanks in advance!
Is there a simple short hand way to easily convert a simple variant to strings without the need to match on every variant?
type currency =
| USD
| CAD
| EUR
Looking to easily add
toString(currency) => string
Thanks in advance!
As variants are represented as int
s I don’t think there is. Would you consider using polymorphic variants? They do provide an easy way to turn them into a string (see this)
Ah, yes this would work just fine, we will move them over to polymorphic variants then
Thanks @alexeygolev
Do you want to use the strings on the ReScript land or JavaScript Land?
They are eventually being used in the JS land, as they need to be passed in as strings to a binding we wrote for Dinero.js.
For interop, the easiest solution is to use polymorphic variants. They are compiled to string literals (unless they have a payload).
type currency = [#USD | #CAD | #EUR]
let usd = #USD
Output:
var usd = "USD";
They don’t work exactly the same as regular variants, so they come with some gotchas, but they are also more flexible.