Small, Simple, Functional Lenses for TypeScript

Building apps in Redux requires frequent updates to nested immutable data structures–something that’s not particularly natural in TypeScript or JavaScript.

The spread operator will get you by, and in JavaScript you can use immutability helper, but there are a few issues with these approaches. Both express updates in terms of deep updates to a data structure, traversing several levels of data that may be sourced from multiple abstraction layers. And immutability helper, alas, is not structured in a way that’s possible to precisely type in TypeScript.

Static functional languages solved this problem long ago with lenses–functional get/set pairs that can be used to read/update values within data structures, composed together, and more. One way to think of them is like a type- and memory-safe functional pointer offset. Given a base structure and an offset in C, I can read from and write to a value within it…except lenses are much safer.

While there are existing lens libraries for TypeScript, the ones I found weren’t exactly what I wanted, so we put together a tiny little lens library for TypeScript, focusing on the following qualities:

  • Small size
  • Static type safety
  • Composition over DSLs
  • Zero dependencies

We’ve published an initial version on GitHub. Check out the readme for examples, or install the NPM package.