Search code examples
ocamlreasonbucklescript

Bs.deriving Abstract getter function returns undefined when using capital names


In the bucklescript doc example for bs.deriving abstract, you can get the property on you created object with nameGet()

This works:

@bs.deriving abstract]
type person = {
  name: string,
  age: int,
  job: string,
};
let joe = person(~name="Joe", ~age=20, ~job="teacher");
let name = nameGet(joe);

If you change it to capitalize the name key like below, your generated getter becomes _NameGet():

type person = {
  _Name: string,
  age: int,
  job: string,
};
let joe = person(~_Name="Joe", ~age=20, ~job="teacher");
let name = _NameGet(joe);

In the second example, the name value comes back undefined. How can that be fixed? example in repl:tryreason


Solution

  • Use [bs.as] to alias the name of the key. This will apparently not change the name of the getter which will remain _NameGet in this case but the value no longer returns undefined.

    [@bs.deriving abstract]
    type person2 = {
      [@bs.as "Name"]
      _Name: string,
      age: int,
      job: string,
    };
    
    let john = person2(~_Name="John", ~age=20, ~job="teacher")
    let namejohn = _NameGet(john);
    Js.log(namejohn);
    

    output: John

    docs: renaming fields