Repository navigation
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 nightly7.1.0-dev.20261106.1, and onmainat6aa91ad401. - The change follows the stable type ordering, not the Go port as a whole: TypeScript 6.0.3 (built from the
v6.0.3tag) checks the code below without errors, but the same build with--stableTypeOrderingproduced 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→inferFromTypeArgumentsrecursion from typescript-go: Infinite recursion in inferFromTypes via getReturnTypeOfSignature (tsc 5.9 OK) #64701, undergetVariances. 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.3tsconfig.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_DepthLimitevents, all atinstantiationDepth: 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
markerSubTypewith constraintFn, or the intersectionNext<?, ?> & ?built from it. So the limit is reached while measuring variances. - 47,098
recursiveTypeRelatedTo_DepthLimitevents.
🙂 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,
CompareTypessorts union members byTypeFlagsvalue first (getSortOrderFlags).TypeFlagsConditional(1<<26) is smaller thanTypeFlagsIntersection(1<<28). So in a union likeInner<…> | TAcc & Wrap<…>, the conditional member comes first. That union is the default constraint of the recursiveInnerconditional 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 forTree.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_DepthLimittrace events47,098 0 instantiateType_DepthLimittrace events36 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 evaluatingIsEqualat each newInnerlevel:getConditionalTyperelates<G>() => G extends A & G | G ? 1 : 2to its counterpart, which goes throughinstantiateSignatureInContextOf, inference,inferFromMatchingTypesandisTypeIdenticalToon the growingNextchains. (instrumented build)
What I think happens (not proven)
- Background:
Falseresults go into the relation cache directly.Mayberesults 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
Innerchain depth-first and collects manyMaybesub-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 theInnerexplorations 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.typesbaselines change, all in the display order of union members:inferenceWithNeverSource1,generatorYieldContextualTypeandpropTypeValidatorInference. 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 beforebooleanin 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
-
[7.0 regression] Unbounded type relation expansion during variance computation causes OOM #64423 (open): TS7 OOM during variance measurement, where 6.0.3 with
--stableTypeOrderingalso runs out of memory. I checked whether it has the same cause as this report:- The one-line change from PR Prevent unbounded combined-constraint recursion during variance measurement #64528 (skip the combined-constraint check while measuring variances) does not change this repro: still TS2589, same instantiation count.
- The ordering change above does not change the reduced test from PR Prevent unbounded combined-constraint recursion during variance measurement #64528. On
main, compiled as a single file withnoEmit, it ends with TS2590 after about 11 s, with and without the ordering change. With Prevent unbounded combined-constraint recursion during variance measurement #64528 applied it finishes in under 0.1 s.
So the two look like separate problems, even though both depend on the order.
-
7.1 regression: comparing a recursive
-?mapped type is quadratic in the number of properties and hits TS2589 (since typescript-go#4820) #64950 (open): also TS2589 during variance computation, after typescript-go#4820 changed the order of variance computation in 7.1. That change is not in 6.0.3, and 6.0.3 with--stableTypeOrderingalready does not finish here, so I don't think this report is the same problem. -
Root file order causes tsgo to miss recursive conditional type assignability error #63859: I understand that order-dependent behavior is expected, and that a result reproducible with some ordering in TS6 is not considered a TS7 bug. I'm still reporting this because the difference here is large (1.9M vs. about 70K instantiations, for the same variance results) and the repro is small and has no dependencies. Under stable ordering, the code always fails.
Activity
RyanCavanaugh commentedon Nov 9, 2026
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.typescript-automation commentedon Nov 12, 2026
This issue has been marked as "Not a Defect" and has seen no recent activity. It has been automatically closed for house-keeping purposes.