Skip to content

TS2589 in 7.1 on code that 5.9 and 6.0 accept, caused by stable union ordering (6.0 with --stableTypeOrdering does not finish) #65365

Closed as not planned

Description

🔎 Search Terms

stable type ordering, stableTypeOrdering, TS2589, excessively deep, variance, union ordering, conditional type, intersection, getSortOrderFlags, CompareTypes, relation cache, Maybe

🕗 Version & Regression Information

  • This changed between versions 6.0.3 and 7.1. Reproduces with 7.1.0-beta, with the nightly 7.1.0-dev.20261106.1, and on main at 6aa91ad401.
  • The change follows the stable type ordering, not the Go port as a whole: TypeScript 6.0.3 (built from the v6.0.3 tag) checks the code below without errors, but the same build with --stableTypeOrdering produced no result within 120 s.
  • TypeScript 5.9.3: no errors.
  • TypeScript 7.0.2 does not reach this problem. It ran for more than 5 minutes without finishing. A goroutine dump taken after 30 s shows the inferFromTypes → inferFromTypeArguments recursion from typescript-go: Infinite recursion in inferFromTypes via getReturnTypeOfSignature (tsc 5.9 OK) #64701, under getVariances. 7.1 no longer has that recursion (fixed by Cache inferences made from type arguments #64553).

⏯ Playground Link

No response

💻 Code

type IsEqual<A, B> =
    (<G>() => G extends A & G | G ? 1 : 2) extends
    (<G>() => G extends B & G | G ? 1 : 2)
        ? true
        : false;

type Fn = (...args: any) => any;
type Next<TFn extends Fn, TStack extends Fn> = (...args: Parameters<TStack & TFn>) => ReturnType<TStack & TFn>;
type Wrap<TFn extends Fn> = TFn extends unknown ? TFn : () => void;

type Inner<TFn extends Fn, TAcc extends Fn, TStack extends Fn, TPrevious extends Fn, TCurrent extends Fn = Next<TFn, TStack>> =
    IsEqual<TCurrent, TPrevious> extends true ? TAcc : Inner<TFn, TAcc & Wrap<TCurrent>, TCurrent & TStack, TCurrent>;

type OwnProperties<T> = { [K in keyof T]: T[K] };
type Unwrap<TFn> = TFn extends Fn ? TFn : TFn;

type Tree<T> = T extends Fn
    ? Unwrap<Inner<T, Wrap<T>, T, T>> & Tree<OwnProperties<T>>
    : T;

interface Client<T> {
    call: Tree<T>;
}

declare let a: Client<Fn>;
declare let b: Client<() => void>;
a = b; // TS2589 in 7.1; no error in 5.9.3 and 6.0.3

tsconfig.json:

{
  "compilerOptions": { "target": "ES2015", "strict": true, "noEmit": true, "types": [] },
  "files": ["test.ts"]
}

Run with tsc -p . --extendedDiagnostics.

The code is a reduction of the repro in #64701 (IsEqual is type-fest's version). It is artificial: I have not seen it in real-world code apart from that report.

🙁 Actual behavior

test.ts(27,1): error TS2589: Type instantiation is excessively deep and possibly infinite.
Instantiations: 1903364
Check time:      0.447s

The output is the same for 7.1.0-beta, the nightly and main.

The error comes from the instantiation depth limit, not from the 5,000,000 instantiation cap. A trace from main (--singleThreaded --generateTrace) shows:

  • 36 instantiateType_DepthLimit events, all at instantiationDepth: 100. The first one occurs after about 32,000 instantiations.
  • The type being instantiated at the limit is a substitution type for the variance marker markerSubType with constraint Fn, or the intersection Next<?, ?> & ? built from it. So the limit is reached while measuring variances.
  • 47,098 recursiveTypeRelatedTo_DepthLimit events.

🙂 Expected behavior

No error, as in 5.9.3 and 6.0.3. () => void is assignable to (...args: any) => any, so Client<() => void> should be assignable to Client<Fn>.

Additional information about the issue

Results

All runs use the code above with tsc -p . --extendedDiagnostics.

Compiler Result Instantiations
TypeScript 5.9.3 no errors 36,150
TypeScript 6.0.3 (built from v6.0.3) no errors 106,956
TypeScript 6.0.3 with --stableTypeOrdering stopped after 120 s, no output –
TypeScript 7.0.2 stopped after 5 min (#64701 recursion, see above) –
TypeScript 7.1.0-beta and 7.1.0-dev.20261106.1 TS2589 1,903,364
main 6aa91ad401 TS2589 1,903,364
main + the candidate change below no errors 70,319

What I measured

  • With stable ordering, CompareTypes sorts union members by TypeFlags value first (getSortOrderFlags). TypeFlagsConditional (1<<26) is smaller than TypeFlagsIntersection (1<<28). So in a union like Inner<…> | TAcc & Wrap<…>, the conditional member comes first. That union is the default constraint of the recursive Inner conditional type (the union of its two branches). With type-ID ordering the intersection happened to come first.

  • The trigger is the variance computation for Client, which nests the variance computation for Tree. Tree<T> on its own is fine. (instrumented build)

  • The measured variances are the same under both orders (instrumented build):

    • Inner: [independent (unreliable), out, independent (unreliable), in out, independent (unreliable)]
    • Tree: out (unreliable)
    • Client: out (unreliable)

    Only the amount of work differs:

    Counter stable order (main) intersections ranked before conditionals
    recursiveTypeRelatedTo_DepthLimit trace events 47,098 0
    instantiateType_DepthLimit trace events 36 0
    calls to structuredTypeRelatedTo (instrumented build) 81,320 16,321
    repeated comparisons of an already-compared (source, target, relation) (instrumented build) 44,669 66
    comparisons returning Maybe (instrumented build) 48,857 1,713
  • The most repeated comparisons are identity comparisons between Next<…> types, 45 times each. They come from evaluating IsEqual at each new Inner level: getConditionalType relates <G>() => G extends A & G | G ? 1 : 2 to its counterpart, which goes through instantiateSignatureInContextOf, inference, inferFromMatchingTypes and isTypeIdenticalTo on the growing Next chains. (instrumented build)

What I think happens (not proven)

  • Background: False results go into the relation cache directly. Maybe results produced under deep-nesting assumptions are kept only if the outermost comparison succeeds, and are dropped when it fails.
  • My guess: with the conditional member first, the checker explores the recursive Inner chain depth-first and collects many Maybe sub-results. Then a cheaper member fails, the sub-results are dropped, and the next attempt recomputes them. With the intersection first, the cheaper member fails before that exploration starts.

What does not fit a simple explanation: I could not find a single union consumer that accounts for the difference.

  • Deferring conditional members in eachTypeRelatedToType (when not reporting errors) removes the Inner explorations there, but not the blowup.
  • Forcing intersections-first iteration in all the consumers I instrumented together cuts instantiations from 1.9M to 650K, but TS2589 remains. Those consumers were eachTypeRelatedToType, typeRelatedToSomeType, someTypeRelatedToType, eachTypeRelatedToSomeType, mapType, alias distribution, base constraints and inference over unions.

So the stored order seems to matter beyond iteration in those functions, for example for which results get cached and when.

One possible mitigation

I am not proposing this as the fix. A change in how Maybe results are kept, or in the variance computation, may be the better place. But ranking intersections before conditional types in the sort order is enough for this repro:

--- a/tsc/internal/checker/utilities.go
+++ b/tsc/internal/checker/utilities.go
@@ -629,6 +629,10 @@ func getSortOrderFlags(t *Type) int {
 	if t.flags&(TypeFlagsEnumLiteral|TypeFlagsEnum) != 0 && t.flags&TypeFlagsUnion == 0 {
 		return int(TypeFlagsEnum)
 	}
+	// Order intersections before conditional types.
+	if t.flags&TypeFlagsIntersection != 0 {
+		return int(TypeFlagsConditional) - 1
+	}
 	return int(t.flags)
 }
  • The repro above checks without errors (70,319 instantiations, see the table). The same holds for the ReturnType<typeof createHandler> form from typescript-go: Infinite recursion in inferFromTypes via getReturnTypeOfSignature (tsc 5.9 OK) #64701 (the test file from PR Add regression test for inference recursion hang #65362, see below).
  • In go test ./internal/testrunner/ (13,806 compiler and conformance cases pass), only 3 .types baselines change, all in the display order of union members: inferenceWithNeverSource1, generatorYieldContextualType and propTypeValidatorInference. No error baseline changes.
  • The new sort value puts intersections directly before conditional types, so they now also sort before union-flagged types. Only the first of the 3 baselines is an intersection/conditional case ((T & Paths<R["p"]>) | Paths<R["p"]>). The other two are intersections moving before a union enum ((T & number) | Directive) and before boolean in a type argument list.
  • It is a heuristic. It helps when the conditional member is the expensive one, and could make cases slower where the intersection is the expensive member. It also changes how some types are printed, as the baselines show.

Relation to #64701 / PR #65362

PR #65362 adds a regression test for #64701 (inferFromTypeArgumentsNoInfiniteRecursion.ts) and does not change the compiler. The test terminates on main, and the PR's error baseline records this TS2589 at type R = ReturnType<typeof createHandler>. With the change above, that file checks without errors, so the baseline would need an update if both land.

Related issues

Activity

  1. added
    Not a Defect
    on Nov 9, 2026
  2. RyanCavanaugh commented on Nov 9, 2026

    @RyanCavanaugh
    Member

    This is not a TS7 regression: TypeScript 6 has the same pathological behavior with --stableTypeOrdering, and TS7 intentionally makes that ordering stable. Reporting TS2589 is preferable to the prior non-terminating check.

  3. typescript-automation commented on Nov 12, 2026

    @typescript-automation
    Contributor

    This issue has been marked as "Not a Defect" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a Defect

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions