Skip to content

Template literal union type-checking is exponentially slower when type is explicitly annotated vs inferred #63653

Closed
microsoft/typescript-go
#4711

Description

@LangLangBart

🔎 Search Terms

"typeMaybeAssignableTo", "getAssignmentReducedType",
"getAssignmentReducedTypeWorker", "template literal union type-checking
performance", "filterType big union", "flow-based narrowing large template literal union"

🕗 Version & Regression Information

  • Reproduces on TS 5,6,7 (did not test version 4 and below)

⏯ Playground Link

https://github.com/LangLangBart/ts-repro-union

💻 Code

(see the reproduction repo linked above)

I have the repro.ts and a TypeName.d.ts with a 40k string literals

// repro.ts
new class {
  private map: Record<string, TypeName[]> = { x: ['f_0|i_0'] }

  constructor() {
    let item: TypeName | undefined
    if (this.map.x) {
      const [entry] = this.map.x
      item = entry
    }
    console.log('item:', item)
  }
}()
// repro-inferred.ts
new class {
  private map: Record<string, TypeName[]> = { x: ['f_0|i_0'] }

  constructor() {
    let item             // <== inferred, no explicit annotation (this is the ONLY difference to 'repro.ts')
    if (this.map.x) {
      const [entry] = this.map.x
      item = entry
    }
    console.log('item:', item)
  }
}()
// TypeName.d.ts
type TypeName = `${Prefix}${Suffix}`;
type Prefix =
    "f_0|" |
    "f_1|" |
    "f_2|" |
    ...
    "f_198|" |
    "f_199|";
type Suffix =
    "i_0" |
    "i_1" |
    ...
    "i_198" |
    "i_199";

🙁 Actual behavior

Type-checking takes ~30s for TS 6.0.3 and ~10s for TS 7.0.2 on a single file with
a 40k-union template literal type.

The runtime scales relative to the template dimension n (members = n²):

repro.ts

n members TS 6.0.3 (ms) TS 7.0.2 (ms)
50 2500 971 458
100 10000 2468 826
150 22500 9433 3040
200 40000 27515 8852

Skipping the item assignment as seen in the repro-inferred.ts runs much
faster and wont scale exponentially.

repro-inferred.ts

n members TS 6.0.3 Inferred (ms) TS 7.0.2 Inferred (ms)
50 2,500 798 415
100 10,000 816 405
150 22,500 892 407
200 40,000 842 407

🙂 Expected behavior

The type assignment should not slow things down and should run as fast as the
inferred file (repro-inferred.ts).

Additional information about the issue

Related issue: #63342

Activity

  1. added
    Needs Investigation
    on Jul 16, 2026
  2. RyanCavanaugh commented on Jul 16, 2026

    @RyanCavanaugh
    Member

    This might not be a bug; // repro-inferred.ts really does have to do less work than // repro.ts - the latter has to do an assignability check, the former does not.

  3. LangLangBart commented on Jul 19, 2026

    @LangLangBart
    Author

    This might not be a bug; // repro-inferred.ts really does have to do less work than // repro.ts - the latter has to do an assignability check, the former does not.

    Tried to profile where the CPU spends the most time for tsc6, most work occurs around isTypeRelatedTo / isFreshLiteralType / isSimpleTypeRelatedTo and typeMaybeAssignableTo.

    The exponential behavior was the reason to call it a bug.

    Image
    # https://github.com/LangLangBart/ts-repro-union
    npx tsc6 --generateCpuProfile tsc6.cpuprofile
    npx tsc6 --generateCpuProfile tsc6.inferred.cpuprofile --project tsconfig.inferred.json
    
    profile() {
      jq -r '"\((.endTime - .startTime) / 1e4 | round/100)s" as $dur |
        [.nodes[] | {key: (.callFrame.functionName|sub("^$";"(anonym)")), value: .hitCount}] |
        group_by(.key) | map({key: .[0].key, value: [.[].value]|add}) | . as $all |
        ($all | sort_by(-.value)[:8])
          + [{key: "== TOTAL ticks ==", value: [$all[].value]|add}]
          + [{key: "== TOTAL duration ==", value: $dur}] |
        .[] | join("\t")' "$1" | column -ts $'\t'
    }
    
    printf "==> repro.ts\n"
    profile tsc6.cpuprofile
    printf "\n==> repro-inferred.ts\n"
    profile tsc6.inferred.cpuprofile

    CPU time spent:

    ==> repro.ts
    (anonym)                7843
    isTypeRelatedTo         5599
    isFreshLiteralType      3698
    isSimpleTypeRelatedTo   3180
    typeMaybeAssignableTo   518
    isUnknownLikeUnionType  424
    (garbage collector)     40
    getPropertyOfType       14
    == TOTAL ticks ==       21754
    == TOTAL duration ==    27.29s
    
    ==> repro-inferred.ts
    (garbage collector)         36
    addInheritedMembers         16
    getStringLiteralType        14
    getReducedApparentType      11
    recursiveTypeRelatedTo      9
    scan                        9
    getUnionTypeFromSortedList  7
    (anonym)                    6
    == TOTAL ticks ==           490
    == TOTAL duration ==        0.63s
  4. ahejlsberg commented on Jul 23, 2026

    @ahejlsberg
    Member

    The culprit here is the getAssignmentReducedType in control flow analysis which can exhibit quadratic behavior when the declaredType and assignedType arguments are both large union types. There's a simple optimization that dramatically reduces the overhead. I'll put up a PR.

  5. added
    Bug
    and removed
    Needs Investigation
    on Jul 23, 2026
  6. LangLangBart commented on Jul 24, 2026

    @LangLangBart
    Author

    There's a simple optimization that dramatically reduces the overhead.

    Thx. Tested the latest nightly with your fix vs the day prior on the repro repo:

    npx envinfo --system
    # System:
    #   OS: macOS 15.7.7
    #   CPU: (10) arm64 Apple M1 Pro
    #   Memory: 9.00 GB / 32.00 GB
    
    hyperfine --warmup 2 -L VER 7.1.0-dev.20260724.1,7.1.0-dev.20260723.1 'npx -y typescript@{VER}'
    # Benchmark 1: npx -y typescript@7.1.0-dev.20260724.1
    #   Time (mean ± σ):     599.0 ms ±   6.5 ms    [User: 663.6 ms, System: 118.0 ms]
    #   Range (min … max):   592.8 ms … 613.9 ms    10 runs
    
    # Benchmark 2: npx -y typescript@7.1.0-dev.20260723.1
    #   Time (mean ± σ):      9.149 s ±  0.034 s    [User: 9.201 s, System: 0.207 s]
    #   Range (min … max):    9.126 s …  9.235 s    10 runs
    
    # Summary
    #   npx -y typescript@7.1.0-dev.20260724.1 ran
    #    15.28 ± 0.18 times faster than npx -y typescript@7.1.0-dev.20260723.1

    ✅ Issue fixed

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

Metadata

Metadata

Labels

Bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions