Typescript - Manipulating Deeply Nested Immutable Objects with Lenses

Posted on January 29, 2020

Javascript doesn’t really have an immutable object but with typescript I can prevent compilation if there’s a rogue function that will try to mutate an object.

Let’s say I have this object, and let’s assume the values are always there because if I start talking about the possibility of null then I have to talk about prisms. So let’s take it easy and stick with lenses for now.

It has this type.

Accessing a value

Without using any library I can manipulate this object no problem. When I want to access a field, I just do the dot syntax and it gives me the value of that field.

Setting a new value and returning the whole object

It becomes a hassle when I have to set a new value.

Applying a function and returning the whole object

Same ugliness can be seen when applying a function to the field.


Lenses to the rescue! Unfortunately I don’t think it’s possible or at least easy to generate lenses based on the objects like what makeLenses does, so I have to hand code all of them.

Well… accessing a value with monocle-ts looks pretty verbose.

I guess I can do it like this

but I think it’s better to just use the dot syntax, at least in my opinion.

Lenses shine when it comes to updating and applying a function to a deeply nested value.

Setting a value and returning the whole object

I think that looks a lot cleaner than using Object.assign.

Applying a function and returning the whole object

Yep. That definitely looks a lot cleaner.

Resources on Lenses

Optics by Example by Chris Penner