The spread operator works only on record type creation, but not on record value creation.
This works:
type foo = {x: int, y: int}
type bar = {...foo, z: int}
But this is not supported:
let foo = {x: 1, y: 2}
let bar: bar = {...foo, z: 3}
I got this error message:
This has type: foo. But it's expected to have type: bar
fham
2
Yes, you cannot safely spread here.
That only works when bar
’s own fields are all optional.
type foo = {x: int, y: int}
type bar = {...foo, z?: int}
let foo = {x: 1, y: 2}
let bar: bar = {...foo, z: 3}
Also, you can spread a supertype like bar
into its subtype:
type foo = {x: int, y: int}
type bar = {...foo, z: int}
let bar = {x: 1, y: 2, z: 1}
let foo = {...bar, y: 3}
but this erases all fields that are not in foo
.
1 Like