Search code examples
reasonrescript

Rescript Record: Key as Array


In Rescript, one can define a Record in this format:

type record1 = {
   a : String
}

but NOT:

type record2 = {
   [a] : String
}

I am looking to write a record that compiles to JS like:

{
   [Op.or]: [12,13]
}

The use case above comes from Sequelize, and the reference is here.

My current solution:

%raw(`{[Op.or]:[12,13]}`)

Solution

  • It's not entirely clear how you intend to interface with the Op construct, whether you can bind to it or not, but here's an example that does, and along with Js.Dict.t effectively produces the same output:

    module Op = {
      @val external or: string = "Op.or"
    }
    
    Js.Dict.fromList(list{
      (Op.or, [12, 23])
    })
    

    It does not directly compile to the JS you want, however, which might be a problem if you rely on something that actually parses the source code. But short of that, I believe this should do what you ask for.