diff --git a/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go index 4ae35a70bb66e..d88dbc209fabf 100644 --- a/tsc/internal/checker/checker.go +++ b/tsc/internal/checker/checker.go @@ -17727,6 +17727,19 @@ func (c *Checker) getConstraintOfIndexedAccess(t *Type) *Type { } func (c *Checker) getConstraintFromIndexedAccess(t *Type) *Type { + d := t.AsIndexedAccessType() + if d.resolvedConstraint == nil { + // The constraint is cached because it can be expensive to compute (e.g. when the index type is constrained + // to a large union) and type relations may request it many times, such as once per constituent of a target union. + d.resolvedConstraint = core.OrElse(c.computeConstraintFromIndexedAccess(t), c.noConstraintType) + } + if d.resolvedConstraint != c.noConstraintType { + return d.resolvedConstraint + } + return nil +} + +func (c *Checker) computeConstraintFromIndexedAccess(t *Type) *Type { d := t.AsIndexedAccessType() if c.isMappedTypeGenericIndexedAccess(t) { // For indexed access types of the form { [P in K]: E }[X], where K is non-generic and X is generic, diff --git a/tsc/internal/checker/types.go b/tsc/internal/checker/types.go index cb328e5c3cb98..4a06e5ca70465 100644 --- a/tsc/internal/checker/types.go +++ b/tsc/internal/checker/types.go @@ -1539,9 +1539,10 @@ func (t *IndexType) Target() *Type { return t.target } type IndexedAccessType struct { ConstrainedType - objectType *Type - indexType *Type - accessFlags AccessFlags // Only includes AccessFlags.Persistent + objectType *Type + indexType *Type + accessFlags AccessFlags // Only includes AccessFlags.Persistent + resolvedConstraint *Type } func (t *IndexedAccessType) ObjectType() *Type { return t.objectType } diff --git a/tsc/testdata/tests/cases/compiler/indexedAccessConstraintRelatedToLargeUnion.ts b/tsc/testdata/tests/cases/compiler/indexedAccessConstraintRelatedToLargeUnion.ts new file mode 100644 index 0000000000000..9d78dc042b5f0 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/indexedAccessConstraintRelatedToLargeUnion.ts @@ -0,0 +1,20 @@ +// @strict: true +// @noEmit: true +// @noTypesAndSymbols: true + +// https://github.com/microsoft/TypeScript/issues/65654 + +type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; +type Table = `t${Digit}${Digit}`; // 100 tables +type TableColumn = "id" | "name" | `${T}_c${Digit}`; // 12 columns per table + +type ColumnMap = { [T in Table]: TableColumn }; +interface Columns extends ColumnMap {} +type Column = TableColumn; +type ColumnFor = Columns[T]; + +declare function parent(column?: C): C; + +export function parentOf(column: ColumnFor) { + return parent(column); +}