What's the meaning of bs.deriving

I couldn’t find any explanations in the docs, so what is the meaning of that code

    /* Supported locales */

    @bs.deriving({jsConverter: newType})

    type locale = [@bs.as("zh") #CH | @bs.as("ru-RU") #RUS | @bs.as("sv-SE") #SWE | @bs.as("en-US") #US]

I found it here https://github.com/reason-association/rescript-lang.org/blob/master/bindings/IntlDateTimeFormat.res

Commits tells me that this are “bindings migrated to Rescript syntax”

The @bs.deriving({jsConverter: newType}) decorator generates an abstract type abs_locale and two functions let localeFromJs: abs_locale => locale and let localeToJs: locale => abs_locale (based on type locale) to be able to make the value on the JS side abstract to the consumer. It also allows aliasing poly-variant constructors to different JS values (e.g. #RU to ru-RU).

The abstract type is a tool to define interfaces, for example in the same binding file, the abs_locale type was used to create a binding like this:

@bs.new @bs.scope("Intl")
  external dateTimeFormat: (abs_locale, option<options>) => intl = "DateTimeFormat"

This means that if you’d want to use dateTimeFormat, you’d need to use localeToJs to convert a #CH value to an abstract abs_locale first. It’s a way to hide implementation details of certain types.

1 Like

As much as I appreciate you taking the time for try to explain me what is happening here, I have to admit that I still have a hard time to grasp whats going on here. To say it very blunt, I looks like complex indirections to a final aim I not fully understand either. So is there more documention on this?

That’s literally the reason why we think this feature shouldn’t be very prominent in the docs, since even if you know that feature, or get a very thorough explanation on what it is, you will still always look it up everytime you need to read such code (or you don’t know why you need it, or why this feature exists). Some of the existing bs.deriving functionality got obsolete, some of it has some very few use-cases where they might be useful, that’s why we tried to reduce the docs surface by temporarily removing them (the object / function bindings docs were already the most complex part of the docs).

We will eventually add a revisited version of the bs.deriving docs later on, probably when the new syntax lookup widget feature will land (currently a WIP PR in the rescript-lang.org repo). This will cover all existing decorators, plus their different variants. It makes more sense there, bc we often just don’t know where and when to look for that feature, and the algolia site search doesn’t help pointing to exact definitions of a decorator either, because it also indexes all occurrences within examples, api docs, etc.

1 Like