fp-ts / optic

A porting of zio-optics to TypeScript
https://fp-ts.github.io/optic/
MIT License
113 stars 3 forks source link

How to add a new field to an object focused on by Lens? #73

Open parkernilson opened 6 months ago

parkernilson commented 6 months ago

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 2 months ago

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.