1

Can i access nested properties with monocle-ts in a dynamic fashion?

The closest i can find directly from the library is the Optional.fromPath, combined with a dynamic path. Based on the example from the documentation for fromPath we can create a small utility function for that specific parent object. However, then you need to type the path.

There is a way to recursively create path types from an object type. However, this also leads to an error.

const responsePath = (path: Paths<Reponse>) => Optional.fromPath<Response>()(path);
// type ["info", "employment"] is not assignable to type "info"

Code for creating a path type:

    type Cons<H, T> = T extends readonly any[] ?
    ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never
    : never;

    type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
        11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]]
    
    type Paths<T, D extends number = 10> = [D] extends [never] ? never : T extends object ?
        { [K in keyof T]-?: [K] | (Paths<T[K], Prev[D]> extends infer P ?
            P extends [] ? never : Cons<K, P> : never
        ) }[keyof T]
        : [];

Summary: Optional.fromPath doesn't work out of the box to dynamically select paths. Is there a way to create a function like the above "responsePath" with Optional.fromPath or other methods from monocle-ts?

1
  • 1
    Doesn't look like it, unfortunately. OptionalFromPath hard codes overloads for up to 5 paths, but doesn't have an overload for the general case of any array of paths. Commented Apr 14, 2022 at 12:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.