0

我可以以动态方式访问带有 monocle-ts 的嵌套属性吗?

我可以直接从库中找到的最接近的是 Optional.fromPath,并结合了动态路径。根据fromPath文档中的示例,我们可以为该特定父对象创建一个小型实用程序函数。但是,您需要输入路径。

有一种方法可以从对象类型递归地创建路径类型。但是,这也会导致错误。

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

创建路径类型的代码:

    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]
        : [];

摘要: Optional.fromPath 不能开箱即用地动态选择路径。有没有办法使用 Optional.fromPath 或来自 monocle-ts 的其他方法来创建类似于上述“responsePath”的函数?

4

0 回答 0