Javascript object field is a ReasonML keyword

interop

#1

I’m writing a binding to a javascript library. I’m receiving an object from the library whose reason definition should look something like this: {. "name": string, "from": int, "to", int }. However, when I try to access the “to” field, via x##to I get a compilation error about to being a keyword.

The workaround that I’ve come up with is defining the object as a Js.Dict.t(string), however, that has the downside of treating everything in the object as a string, which isn’t correct either (but at least works, AFAICT).

Is there a better way?


#2

Here’s a hack that could work for you I think https://github.com/BuckleScript/bucklescript/issues/2228#issuecomment-369447632


#3

A) thanks

B) I agree you’re running into the same issue with “attributes” that I am with “to”, but I don’t see a hack/solution in that thread. Probably because I can’t understand a decent chunk of it.


#4

Oh it’s not rocket science! Say you have

type t;

[@bs.val] external myObj : t = "myObj"; /* a JS object like { to: 10 }; */

Then you can access that field by writing an external like:

[@bs.get_index] external getTo: t => ([@bs.as "to"] _) => int = "";

let thisIsTen = getTo(myObj); /* This literally becomes `let thisIsTen = myObj["to"];` */

#5

Amazing! Thanks :slight_smile:


#6

Actually, here’s better way to share and try things haha: https://reasonml.github.io/en/try.html?rrjsx=true&reason=C4TwDgpgBMDcBQ8DaABARgZwHQDcCGANgLpQQAewEATgHaFQC2IA8mgFZQBcMUAvFACImrNgITJ02AOYRgAfQCWNACbkS5SrXozgAFQD23YHwB8UABSpMWPBkHB9AknICUpqEuP8BYxAVkwABYKGACSGLoQNHxQOgbmwuwusEA


#7

BuckleScript has a little trick where it strips a prefixed underscore from field names that would be invalid identifiers in OCaml/Reason, but valid in JavaScript. So you can do: x##_to.


#8

And the corresponding documentation: https://bucklescript.github.io/docs/en/object.html#name-mangling


#9

Even better. Thanks!