Function getLens

  • Get an OptionalLens<T, T> for type-safe access on arbitrarily nested properties of type T, where T might be a union of arbitrary types.

    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

    Returns OptionalLens<T, T>

Generated using TypeDoc