How to model JavaScript dynamic fields?

Hi, I am new to rescript. I am trying to bind for an external js library, but i have a problem with the dynamic.

This external function accepts an option argument, which might look like this:

const res = lib.create({ // ..., 
  onClick: () => {console.log(...)} 
})
const res = lib.create({ // ..., 
  onClick: false
})
const res = lib.create({ // ..., 
  onClick: {
    exit: () => {}
  }
})
type options = {
  // ...
  onClick: | false 
           | () => unit 
           | { 
                pre: option<() => unit>,
                on: option<() => unit>,
                exit: option<() => unit> 
              }
}

How to model such an object? I want to get type safety while having better ide code hints.

Thanks!

This doc might be helpful.

Hi, I usually do something like the following in cases like this. Still not sure this is the best way to handle this, though.

Playground

module Callback = {
  type t

  %%private(external ofBool: bool => t = "%identity")

  let none = ofBool(false)

  external ofFun: (unit => unit) => t = "%identity"

  @obj
  external ofMany: (
    ~pre: unit => unit=?,
    ~on: unit => unit=?,
    ~exit: unit => unit=?,
    unit,
  ) => t = ""
}

type options = {onClick: Callback.t}

let options1 = {onClick: Callback.none}

let options2 = {onClick: Callback.ofFun(() => Js.log("hello"))}

let options3 = {onClick: Callback.ofMany(~pre=() => Js.log("hello"), ())}
3 Likes

Thanks, I think this is a great idea!

1 Like