microsoft / microsoft/TypeScript

type checking complexity with multiple template literals in unions

Open
#63,342 5 comments 0 reactions 0 assignees View on GitHub
Domain: check: Big Unions Experimentation Needed Possible Improvement
Dominant language
Go
Stars
111k
Forks
14.3k
PR merge metrics
PR metrics pending

Description

### 🔎 Search Terms

template literals, performance

### 🕗 Version & Regression Information

4.1 introduced template literals where `tsc` fails with `RangeError: Map maximum size exceeded`.
4.5 is the first version that completes where typechecking time already scales exponentially.

### ⏯ Playground Link

https://github.com/eps1lon/repro-ts-template-literals-complexity

### 💻 Code

The example is based on how Next.js typechecks the `href` in `` components.

```ts
// Example type definitions for Next.js routes

type SearchOrHash = `?${string}` | `#${string}`;
type WithProtocol = `${string}:${string}`;

type Suffix = "" | SearchOrHash;

type SafeSlug = S extends `${string}/${string}`
? never
: S extends `${string}${SearchOrHash}`
? never
: S extends ""
? never
: S;

type StaticRoutes =
| `/next`
| ...;

// comment out union constituents to see exponential impact of dynamic routes
// 6 routes -> 5 -> 4 -> 3
// tsc on M3:
// 45s -> 24s -> 12s -> 6s
// tsgo on M3:
// 9s. -> 5s -> 2.5s -> 0.08s
type DynamicRoutes =
| `/${SafeSlug}/${SafeSlug}/${SafeSlug}`
| `/${SafeSlug}/${SafeSlug}/integrations/${SafeSlug}/${SafeSlug}/resources/${SafeSlug}/${SafeSlug}/billing`
| ...;

type RouteImpl =
| StaticRoutes
| SearchOrHash
| `${StaticRoutes}${SearchOrHash}`
| (T extends `${DynamicRoutes}${Suffix}` ? T : never);

function Link(href: RouteImpl): void {}

Link("/api/ai-playground/sandbox"); // OK
Link("/new/~/integrations/vercel/front/billing"); // OK
```

### 🙁 Actual behavior

Type checking time doubles with every constituent of `DynamicRoutes` with template literals

### 🙂 Expected behavior

Type-checking is reasonably fast

### Additional information about the issue

_No response_

Contributor guide

Open the contributing guide

Research direction

Start with the linked reproduction and the template-literal union example, then compare tsc behavior across the mentioned versions. Measure type-checking time as DynamicRoutes constituents are added, including the RangeError case; done means the exponential slowdown is addressed and the example type-checks reasonably fast.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.