typescript type max recursion limited to 9

Viewed 558

I finally succeed in creating a generic type which give me all possible combinations of json key list / value. I even prepared a method to limite the recursion.

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]

Even with the depth limitation, typescript sends me an error if depth is higher than 9 but I can't understand why? It seems that typescript max recursion is limited to 50 so is there a reason to get the following error :

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

You can limit recursion depth the similar way as lib.es2019.array.d.ts shipped with 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"];
Related