Easily convert variants toString literals

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 ints 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)

1 Like

Ah, yes this would work just fine, we will move them over to polymorphic variants then :+1:

Thanks @alexeygolev

1 Like

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


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.