Type alias OptionalLens<T, P>

OptionalLens<T, P>: {
    compose: (<T2, P2>(lens: OptionalLens<T2, P2>) => OptionalLens<T | T2, P | P2>);
    get: ((value: T) => P | undefined);
    k: (<K>(key: K) => OptionalLens<T, PickReturn<P, K>>);
}

An OptionalLens<T, P> grants type-safe access on potential P, hence it can be used to get P | undefined from an arbitrary T, where T might be a union of arbitrary types.

From an OptionalLens<T, P>, you can also retrieve a new OptionalLens<P, P[K]>, where K is a potential key of P. Use getLens<T>() to get an initial OptionalLens<T, T>.

You can see OptionalLens as "universal optional chaining". While normal optional chaining only works on a T | null | undefined, the OptionalLens allows the type-safe access on arbitrary unions.

E.g. given the following type and values:

type TestChild = boolean | { x: number | Array<number> };
type Test =
| number
| {
a: string | Array<boolean | TestChild>;
};

const t1: Test = 42;
const t2: Test = { a: 'Test3' };
const t3: Test = { a: [true, { x: 7 }, { x: [1, 2, 3] }] };
const t4: TestChild = { x: 7 };

you could get the following results with optional-lenses:

const lensA = getLens<Test>().k('a');
const a1 = lensA.get(t1); // => undefined (inferred as undefined | string | Array<boolean | TestChild>)
const a2 = lensA.get(t2); // => 'Test3' (inferred as undefined | string | Array<boolean | TestChild>)
const a3 = lensA.get(t3); // => [true, { x: 7 }, { x: [1, 2, 3] }] (inferred as undefined | string | Array<boolean | TestChild>)

const lensA2X1 = lensA.k(2).k('x').k(1);
const n1 = lensA2X1.get(t1); // => undefined (inferred as number | undefined)
const n2 = lensA2X1.get(t2); // => undefined (inferred as number | undefined)
const n3 = lensA2X1.get(t3); // => 2 (inferred as number | undefined)

const lensB = getLens<Test>().compose(getLens<TestChild>());
const t3a = lensB.k('a').get(t3); // [true, { x: 7 }, { x: [1, 2, 3] }] (inferred as undefined | string | Array<boolean | TestChild>)
const t4x = lensB.k('x').get(t4); // 7 (inferred as undefined | number | Array<number>)

Type Parameters

  • T

  • P

Type declaration

Generated using TypeDoc