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?