Skip to content

Checking a generic indexed access against a large union of literal aliases takes 16 s on 7.0.2 (5.9 s on 5.9.3) #65654

Done

Description

@AlexandreDemartin

TypeScript Version

The tested TypeScript version is 7.0.2 (also 5.9.3 and 6.0.3). macOS, Apple silicon.

User Goal

The user maintains a TypeScript library that generates types from a Postgres schema, and asked me to narrow down why a small generic helper takes about 13 s to type-check against a large generated schema. The repro keeps the generated shape: one alias per table for its column names, a map from table to alias, and the union of all aliases (about 1,700 names).

Setup and Action

node gen.mjs writes main.ts (about 50 KB) and tsconfig.json. Then run tsc -p . --extendedDiagnostics.

// gen.mjs
import {writeFileSync} from 'node:fs';
const [n = 300, k = 12] = process.argv.slice(2).map(Number);
const tables = Array.from({length: n}, (_, i) => `T${i}`);
const lines = tables.map((t, i) =>
  `type ${t}Column = 'id' | 'name' | ${Array.from({length: k}, (_, j) => `'c${(i * k + j) % 1700}'`).join(' | ')};`);
writeFileSync('main.ts', `${lines.join('\n')}

interface Columns { ${tables.map(t => `${t.toLowerCase()}: ${t}Column;`).join(' ')} }
type Table = keyof Columns;
type Column = ${tables.map(t => `${t}Column`).join(' | ')};
type ColumnFor<T extends Table> = Columns[T];

declare function parent<C extends Column | undefined>(column?: C): C;

export function parentOf<T extends Table>(column: ColumnFor<T>) {
  return parent(column);
}
`);
writeFileSync('tsconfig.json', JSON.stringify({compilerOptions: {strict: true, noEmit: true, types: [], lib: ['es2020']}, files: ['main.ts']}));

The generated main.ts has 300 aliases like type T0Column = 'id' | 'name' | 'c0' | … | 'c11';, then the 9 lines of the template above.

Expected and Actual Behavior

What actually happened: Check time for this one call, parent(column):

Tables (node gen.mjs <n> 12) 5.9.3 7.0.2
100 2.1 s 4.4 s
200 5.0 s 15.2 s
300 5.9 s 16.1 s

Writing the per-table unions inline in Columns, rather than as named aliases, brings the 300-table case to 0.75 s (5.9.3) and 0.93 s (7.0.2).

A CPU profile of 5.9.3 on an equivalent repro has nearly all of the check time (19.4 of 19.7 s, under the profiler) inside getConstraintOfIndexedAccess, called from structuredTypeRelatedTo, and 19.1 s of it in getUnionType: ColumnFor<T>'s constraint appears to be rebuilt for each member of the target union.

What I expected: a check time close to the inline form's, since ColumnFor<T>'s constraint, Columns[Table], is the same union as Column.

Agent Info

Claude Code + Claude Opus 5.5 + Skill Version 1.0

Metadata

Metadata

Labels

Bug

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions