Lenses

A lens is just a pair of functions that allow us to get and set a value in an object. The interface of a lens could be declared as follows:

interface Lens<T1, T2> {    get(o: T1): T2;    set(o: T2, v: T1): T1;}

As we can see in the previous code snippet, the lens generic interface declares two methods. The get method can be used to get the value of a property of type T2 in an object of type T1. The set method can be used for the value of a property with type T2 in an object of type T1. The following code snippet implements the Lens interface: 

const streetLens: Lens<Address, Street> = {    get: (o: Address) => o.street,    set: (v: Street, o: Address) => new Address(o.city, v)};

The preceding implementation of the Lens interface is named streetLens ...

Get Hands-On Functional Programming with TypeScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.