A Lens requires the target field to be mandatory. If you need to zoom into a field that might not exist (e.g., the first character of a string, which is absent if the string is empty), you must use an Optional.
Key Concepts:
- Lens: Used for mandatory fields. Composing two Lenses results in a Lens.
- Optional: A "partial Lens" used for fields that might be missing. Composing two Optionals results in an Optional.
- Interoperability: You can convert a
Lens into an Optional using .asOptional(). Composing an Optional with a Lens always produces an Optional.
This allows you to navigate through mandatory structures and then safely transition into optional paths.
import { Optional } from 'monocle-ts'
import { some, none } from 'fp-ts/lib/Option'
// Define an Optional for the first letter of a string
const firstLetter = new Optional<string, string>(
s => (s.length > 0 ? some(s[0]) : none),
a => s => a + s.substring(1)
)
// Navigate via Lens, convert to Optional, then compose with the Optional lens
company
.compose(address)
.compose(street)
.compose(name)
.asOptional()
.compose(firstLetter)
.modify(s => s.toUpperCase())(employee)