首页 > 解决方案 > 打字稿类型最大递归限制为 9

问题描述

我终于成功地创建了一个泛型类型,它为我提供了 json 键列表/值的所有可能组合。我什至准备了一种限制递归的方法。

type EditAction<T,P extends keyof T,Prev extends any[]> = {
    data : T[P]
    id : [...Prev, P]
    prev : Prev
}

type EditActions<T, Depth extends number = 50, Prev extends any[] = []> = {
    [P in keyof T] : T[P] extends JsonType 
        ? (Prev["length"] extends Depth
            ? EditAction<T,P,Prev>
            : (EditAction<T,P,Prev> | EditActions<T[P],Depth,[...Prev,P]>)) 
        : EditAction<T,P,Prev>
}[keyof T]

即使有深度限制,如果深度高于 9,打字稿也会向我发送错误,但我不明白为什么?似乎打字稿最大递归限制为 50,所以有理由得到以下错误:

Type instantiation is excessively deep and possibly infinite.ts(2589)
(property) payload: EditActions<T, 50, []>

标签: typescriptrecursiontypescript-typings

解决方案


lib.es2019.array.d.ts您可以使用与 TypeScript类似的方式限制递归深度。

type FlatArray<Arr, Depth extends number> = {
    "done": Arr,
    "recur": Arr extends ReadonlyArray<infer InnerArr>
        ? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
        : Arr
}[Depth extends -1 ? "done" : "recur"];

推荐阅读