typescript - 打字稿类型最大递归限制为 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, []>
解决方案
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"];
推荐阅读
- kubernetes - 在 minikube 上使用 kubeflow 从私有谷歌容器注册表中提取图像
- sage - 一组排列的轨道
- html - 选择框选项重叠
- javascript - Vue - 组件背景图片 url 错误
- javascript - Google Chrome 上的 WebSocket 客户端返回错误 1006
- c++ - 使用 AWS 开发工具包链接问题
- c# - REST 资源(文档、集合、存储)和 REST 控制器之间有什么区别?
- firebase - Flutter Web 中的 Firebase 身份验证错误
- javascript - 带有条件状态码的 Angular retryWhen
- c++ - 只有“void”是不可引用的类型吗?