How to add a new field to an object focused on by Lens?
Opened this issue · 1 comments
parkernilson commented
This might not be the right place to post this question, sorry!
But if I have an object pointed to by lens, e.g.:
const objA: A = {
aVal: "a value"
b: {
bVal: "b value"
}
}
const bLens = Optic.id<A>().at("b")
How could I add a new value "anotherBVal"
to b
using optics?
I would like the resulting object to be:
objA: {
aVal: "a value",
b: {
bVal: "b value",
anotherBVal: "another b value",
}
}
Is this possible?
jdharrisnz commented
Hi, you can't do this in a way that TypeScript will be happy with, because anotherBVal
is not part of type A
.
However, that doesn't mean lenses aren't useful here, as long as you're happy to make some assertions or ignore some errors.
The modify
function can be used to do this, like so:
const objB = Optic.modify(bLens)((b) => ({...b, anotherBVal: "another b value"}))(objA)
Value-wise you will have the right thing, but I leave the types up to you, since you'll be breaking the system a bit by doing this.