typescript type_error ai_generated true

TS2589: Type instantiation is excessively deep and possibly infinite

ID: typescript/ts-excessive-stack-depth

Also available as: JSON · Markdown
78%Fix Rate
82%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Recursive type instantiation exceeds the compiler's depth limit. Simplify the type or add a recursion terminator.

generic

Workarounds

  1. 85% success Add a recursion depth limit using a counter type
    type DeepFlatten<T, Depth extends number[] = []> =
      Depth['length'] extends 10 ? T : // limit recursion
      T extends Array<infer U> ? DeepFlatten<U, [...Depth, 0]> : T;

    Sources: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html

  2. 82% success Simplify the type by reducing nesting or using intermediate type aliases
    // Break complex recursive type into smaller parts
    type Step1<T> = /* first transformation */;
    type Step2<T> = /* second transformation */;
    type Final<T> = Step2<Step1<T>>;

    Sources: https://www.typescriptlang.org/docs/handbook/2/types-from-types.html

Dead Ends

Common approaches that don't work:

  1. Use @ts-ignore to suppress the error 75% fail

    The underlying type will be any, and the infinite recursion may slow down the IDE

Error Chain

Leads to:
Preceded by:
Frequently confused with: