DEV Community

Discussion on: Immutably updating JavaScript objects in ReasonML (BuckleScript)

 
yawaramin profile image
Yawar Amin • Edited

It could be handled with a PPX too. E.g. the [@bs.deriving abstract] annotation generates getters and setters for the object type it annotates: bucklescript.github.io/docs/en/obj... . Theoretically it could be extended to also generate a 'copy constructor':

[@bs.deriving abstract]
type person = {id: int, name: string};

// Generate:

let copy = (person, ~id=person##id, ~name=person##name, ()) =>
  {"id": id, "name": name};

// Usage:

let bob = person(~id=1, ~name="Bob");
let bob2 = bob->copy(~id=2, ());
Thread Thread
 
hoichi profile image
Sergey Samokhov

Well, if I correctly understand what record-as-objects is (namely, compiling ML records to JS objects as opposed to JS arrays), your ‘copy constructors’ (or assign constructors or what have you) could still be useful, provided one needs do deal with optional object properties. I mean, you would still probably need [@bs.derivig abstract] if some of your properties are optional, no?

Thread Thread
 
yawaramin profile image
Yawar Amin

If the properties themselves are optional, true! That throws another thorn into the copy constructor generator idea.