Lens<S, A>Focuses on exactly one part A inside a whole S.
When to use
Use when you always have a value to read and need the original S to produce
the updated whole, unlike Iso.
Details
get(s)always succeeds and returnsA.replace(a, s)returns a newSwith the focused part replaced.- Extends Optional.
- Composing a Lens with a Prism or Optional produces an Optional.
Example (Focusing on a struct field)
import { Optic } from "effect"
type Person = { readonly name: string; readonly age: number }
const _name = Optic.id<Person>().key("name")
console.log(_name.get({ name: "Alice", age: 30 }))
// Output: "Alice"Source effect/Optic.ts:1443 lines
export interface interface Lens<in out S, in out A>Focuses on exactly one part A inside a whole S.
When to use
Use when you always have a value to read and need the original S to produce
the updated whole, unlike Iso.
Details
get(s) always succeeds and returns A.
replace(a, s) returns a new S with the focused part replaced.
- Extends
Optional
.
- Composing a Lens with a
Prism
or
Optional
produces an
Optional
.
Example (Focusing on a struct field)
import { Optic } from "effect"
type Person = { readonly name: string; readonly age: number }
const _name = Optic.id<Person>().key("name")
console.log(_name.get({ name: "Alice", age: 30 }))
// Output: "Alice"
Lens<in out function (type parameter) S in Lens<in out S, in out A>S, in out function (type parameter) A in Lens<in out S, in out A>A> extends interface Optional<in out S, in out A>The most general optic — both reading and writing can fail.
When to use
Use when the focus may not exist in S and writing a new A back may also
fail, for example when the source no longer matches the expected shape. This
is the base type extended by
Iso
,
Lens
,
Prism
, and
Details
getResult(s) returns Result.Success<A> or Result.Failure<string>.
replaceResult(a, s) returns Result.Success<S> or
Result.Failure<string>.
replace(a, s) returns the original s on failure (never throws).
modify(f) returns the original s on failure (never throws).
- All operations are pure; inputs are never mutated.
Example (Focusing on an optional record key)
import { Optic, Result } from "effect"
type Env = { [key: string]: string }
const _home = Optic.id<Env>().at("HOME")
console.log(Result.isSuccess(_home.getResult({ HOME: "/root" })))
// Output: true
console.log(Result.isFailure(_home.getResult({ PATH: "/bin" })))
// Output: true
// replace returns original on failure
console.log(_home.replace("/new", { PATH: "/bin" }))
// Output: { PATH: "/bin" }
Optional<function (type parameter) S in Lens<in out S, in out A>S, function (type parameter) A in Lens<in out S, in out A>A> {
readonly Lens<in out S, in out A>.get: (s: S) => Aget: (s: in out Ss: function (type parameter) S in Lens<in out S, in out A>S) => function (type parameter) A in Lens<in out S, in out A>A
}Referenced by 3 symbols