Js.t, ##. macro, Js.Unsafe.{inject, coerce}

I think I have skimmed every page on How to bind a JS library for OCaml 3-4 times by now, but there is still something I do not understand regarding how all this fits together.

  1. Why we do need this phantom type Js.t ?

  2. Why does ##. seem to assume Js.t everywhere ?

  3. How do we get rid of the Js.t i.e. convert to pure-OCaml type ? Is it just Us.Unsafe.{inject, coerce} ?

  4. When is it safe to use Js.Unsafe.{inject, coerce} ?

  5. What else should I read? At this point, I think I’ve written a few thousand lines of code directly using the Js_of_ocaml.Js.* definitions; I’ve also defined my own Js objects via class type object = ... , as well as constructed my own Js objects via object%js (and passed them to JS rust).

Nevertheless, I still don’t feel I understand what Js.t does (i.e. my understanding is more"trial/error" than “from first principles”). Any other suggested reading ?

Thanks!

1 Like

Why we do need this phantom type Js.t ?

I’m assuming you mean phantom type parameter 'a in 'a Js.t
The phantom type is used to type properties (including their read-write permissions) and methods.

Why does ##. seem to assume Js.t everywhere ?

##. just expect a Js.t on the LHS.

For example, o##.prop expect the value o to be of type <prop : 'a Js.prop> Js.t and returns a value of type 'a

You might want to read Ppx syntax extension for Js_of_ocaml

How do we get rid of the Js.t i.e. convert to pure-OCaml type ? Is it just Us.Unsafe.{inject, coerce}

What kind of conversion are you after ? if you’re thinking about js object ↔ ocaml record, you can have a look at GitHub - little-arhat/ppx_jsobject_conv: ppx rewriter for [@@deriving jsobject].

When is it safe to use Js.Unsafe.{inject, coerce} ?

Js.Unsafe.inject should be mostly type “safe”. Js.Unsafe.inject is never type safe, you need to know what you’re doing.