Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
parkernilson opened this issue Dec 15, 2023 · 1 comment
Open

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

parkernilson opened this issue Dec 15, 2023 · 1 comment

Comments

@parkernilson
Copy link

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
Copy link

jdharrisnz commented Apr 26, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants