Skip to content

Excessive stack 深度 comparing 类型

错误信息

                Excessive stack 深度 comparing 类型
              

快速摘要

TypeScript's 类型 checker exceeded 它的 recursion 限制虽然 comparing two 类型. 这个通常 happens 使用 deeply recursive or self-referential 类型.

为什么发生

  • Self-referential 类型定义

  • Deeply nested generic 类型 instantiations

  • Recursive conditional or mapped 类型

  • 复杂类型关系那个创建 deep comparison 链

最小示例

✗ 错误代码
type Deep<T> = { value: T; next: Deep<T>; }; // unbounded recursion
const x: Deep<number> = complexValue;
✓ 修复代码
type Deep<T, D extends number = 5> = D extends 0 ? never : { value: T; next: Deep<T, D - 1> };

添加深度参数到 限制 recursion.

如何诊断

  • Look for recursive 类型定义 (类型那个引用它们自己)

  • 检查 for deeply nested generic instantiations

  • Identify two 类型是 compared in 错误

如何修复

  • Break recursive 类型到 simpler 非-recursive 表单

  • 添加深度限制到 recursive 类型 using conditional 类型

  • Simplify 复杂 generic 链

  • Use 类型 assertions 到 bypass deep comparison 当 safe

如何预防

  • Avoid unbounded recursive 类型

  • Keep generic nesting reasonable

  • Use explicit 类型 annotations for 复杂类型

相关资源

← 返回语言