Skip to content

Lens

Lens: object

Defined in: Core/Lens.ts:24

andThen: <A, B>(inner) => <S>(outer) => Lens<S, B>

Composes two Lenses: focuses through the outer, then through the inner. Use in a pipe chain to build up a deep focus step by step.

A

B

Lens<A, B>

<S>(outer) => Lens<S, B>

const userCityLens = pipe(
  Lens.from.property<User>()("address"),
  Lens.andThen(Lens.from.property<Address>()("city")),
);

andThenOptional: <A, B>(inner) => <S>(outer) => Optional<S, B>

Composes a Lens with an Optional, producing an Optional. Use when the next step in the focus is optional (may be absent).

A

B

Optional<A, B>

<S>(outer) => Optional<S, B>

const userBioOpt = pipe(
  Lens.from.property<User>()("profile"),
  Lens.andThenOptional(Optional.from.property<Profile>()("bio")),
);

from: object

accessors: <S, A>(get, set) => Lens<S, A> = makeAccessors

Constructs a Lens from a getter and a setter.

S

A

(s) => A

(a) => (s) => S

Lens<S, A>

const nameLens = Lens.from.accessors(
  (user: User) => user.name,
  (name) => (user) => ({ ...user, name }),
);

property: <S>() => <K>(key) => Lens<S, S[K]> = makeProperty

Creates a Lens that focuses on a property of an object. Call with the structure type first, then the key.

S

<K>(key) => Lens<S, S[K]>

const nameLens = Lens.from.property<User>()("name");

get: <S, A>(lens) => (s) => A

Reads the focused value from a structure.

S

A

Lens<S, A>

(s) => A

pipe(user, Lens.get(nameLens)); // "Alice"

modify: <S, A>(lens) => (f) => (s) => S

Applies a function to the focused value, returning a new structure.

S

A

Lens<S, A>

(f) => (s) => S

pipe(user, Lens.modify(nameLens)(n => n.toUpperCase())); // "ALICE"

set: <S, A>(lens) => (a) => (s) => S

Replaces the focused value within a structure, returning a new structure.

S

A

Lens<S, A>

(a) => (s) => S

pipe(user, Lens.set(nameLens)("Bob")); // new User with name "Bob"

toOptional: <S, A>(lens) => Optional<S, A>

Converts a Lens to an Optional. Every Lens is a valid Optional whose get always returns Some.

S

A

Lens<S, A>

Optional<S, A>

pipe(
  Lens.from.property<User>()("address"),
  Lens.toOptional,
  Optional.andThen(Optional.from.property<Address>()("landmark")),
);