How to merge two records?

I have two records of the same type. I tried merging them with:

let merged = {
  ...a,
  ...b,
}

But that doesn’t work. I have to manually list out all the fields like:

let merged = {
  ...a,
  field1: b.field1,
  field2: b.field2,
  field3: b.field3,
}

But that is tedious. How do I merge two records easily?

Do you have a concrete example of what you’re trying to do? It doesn’t make sense to merge two records like that.

Consider this example:

type t = {x: int, y: string}
let a = {x: 1, y: "a"}
let b = {x: 2, y: "b"}
let c = {...a, ...b} // What should we expect c to be?

If we do the same idea manually:

let c = {...a, x: b.x, y: b.y}

Then we end up with a record that’s just identical to b, which defeats the idea of a “merge.” In fact, the compiler will even warn you about doing this:

All the fields are already explicitly listed in this record.
You can remove the `...` spread.
2 Likes

Merging multiple records are not supported. But,

There is a POC(https://github.com/rescript-lang/rescript-compiler/pull/5715) about what you need. It probably needs a type extension of record first due to the nominal type system.

We’ll see how it will be landed in future.