Skip to content

Type-checking performance

After M4, Relay’s editor hovers got slow and CI spends longer in tsc than in the tests. Nothing is wrong with the code. The types are doing a lot of work: a dependency bag built from intersections, a recursive config type, unions that multiply. Type-level code is real code, and it has a cost.

The rule for this lesson is the usual one for performance: measure first. A change that looks cheaper in the source often changes nothing, and the slow spot is rarely where you guess.

The tsc in this course is TypeScript 7, the native compiler. Its help lists the diagnostics flags:

Terminal window
./node_modules/.bin/tsc --help --all
### Compiler Diagnostics
--diagnostics
--extendedDiagnostics
--generateCpuProfile
--generateTrace
Generates an event trace and a list of types.
--traceResolution

--extendedDiagnostics exists in this build. Run it on the project and read the counters:

Terminal window
./node_modules/.bin/tsc -p src/exercises --extendedDiagnostics
Files: 327
Lines: 157080
Identifiers: 121642
Symbols: 111823
Types: 15641
Instantiations: 24674
Memory used: 84636K
Memory allocs: 283611
Config time: 0.006s
Parse time: 0.043s
Bind time: 0.012s
Check time: 0.024s
Emit time: 0.000s
Total time: 0.089s

These numbers are from this course’s exercises project. Yours will differ, and that is fine: you compare your own runs against each other. The lines that matter for type work:

  • Check time is where type-level code costs you. If it dominates Total time, the types are the problem.
  • Types and Instantiations count how many types the checker created and how many times it applied a generic to arguments. A change that cuts Instantiations by half is a real win even if the clock is noisy.
  • Files and Lines include lib and node_modules declarations. A huge Files count points at imports or types pulling in too much, and no type refactor will fix that.

Older, JavaScript-based tsc printed more lines (cache sizes, I/O reads). This build printed the list above, so only those are documented here. Plain --diagnostics gives a shorter version of the same report.

When Check time is high, ask which file or type is responsible. --generateTrace takes an output directory and exists in this build:

Terminal window
./node_modules/.bin/tsc -p src/exercises --noEmit --generateTrace ./trace
ls trace
legend.json
trace.json
types_0.json
types_1.json
types_2.json
types_3.json

trace.json is a timeline of what the checker did, in the Chrome trace format, so Perfetto or the browser’s trace viewer opens it. types_N.json lists every type the checker created, one file per checker thread (this run used four, so four files; --checkers sets the number and --singleThreaded uses one). legend.json maps each file to its checker. Look in the timeline for the longest bars, then find the declaration in the matching types file.

Relay’s dependency bag from lesson 1 can be written two ways:

interface QueuePort {
readonly queue: { take(signal: AbortSignal): Promise<string | null> }
}
interface ClockPort {
readonly clock: { now(): number }
}
interface LoggerPort {
readonly logger: { info(msg: string): void }
}
type DepsA = QueuePort & ClockPort & LoggerPort
interface DepsB extends QueuePort, ClockPort, LoggerPort {}

They accept the same objects. The difference is in how the checker handles them. An interface is a named type: it is resolved once and compared by identity and by its cached members. An intersection is built from its parts and compared member by member, and every function that takes DepsA pays for it again. With four or five ports and hundreds of functions, that adds up.

extends also reports conflicts. An intersection hides them:

interface A {
readonly id: string
}
interface B {
readonly id: number
}
type Both = A & B // compiles: `id` is quietly `never`
// @ts-expect-error: Interface 'Bad' cannot simultaneously extend types 'A' and 'B'
interface Bad extends A, B {}

So the interface is faster and catches a real mistake. Keep & for the places it is the right tool: combining at a call site, as in LoggerPort & NotifyPort for one function’s parameter.

Inference is convenient and costs time. Without an annotation, the checker must check the body to learn the return type, and every caller depends on that result. Write it on exports:

interface Job {
readonly id: string
readonly kind: string
}
// Inferred: callers see a type the checker had to compute from the body.
export const parse = (raw: string) => {
const [id = "", kind = ""] = raw.split(":")
return { id, kind }
}
// Annotated: the signature is the contract. Callers read it without looking at the body.
export function parseJob(raw: string): Job {
const [id = "", kind = ""] = raw.split(":")
return { id, kind }
}

The annotation helps in three ways. It speeds up checking for callers. It makes .d.ts output small and readable, so a change inside the body can’t leak into the public type. And the compiler checks the body against your stated type, so an accidental string | undefined shows up at the function, not at some distant caller.

Limit recursion and avoid multiplying unions

Section titled “Limit recursion and avoid multiplying unions”

A recursive type with no stop is slow when the input is deep, and an error when it is self-referential. The Paths type from M4 on a type that refers to itself is rejected: Type of property 'next' circularly references itself in mapped type. Add a counter tuple (variadic tuples) that grows per level and stops at a fixed depth:

type Paths<T, Depth extends readonly unknown[] = []> = Depth["length"] extends 3
? never
: T extends object
? { [K in keyof T & string]: K | `${K}.${Paths<T[K], [...Depth, unknown]>}` }[keyof T & string]
: never
interface Node {
readonly name: string
readonly next: Node
}
const ok: Paths<Node> = "next.next.name"
// @ts-expect-error: a fourth segment is past the limit
const tooDeep: Paths<Node> = "next.next.next.name"

Config trees are shallow, so a limit of three or four costs nothing, and the checker stops.

Unions have a similar trap. Template literals multiply: the result has one member for every combination of the parts.

type Kind = "email" | "sms" | "push" | "webhook"
type Status = "queued" | "running" | "done" | "failed"
type Region = "eu" | "us" | "ap"
type EventName = `${Kind}.${Status}.${Region}` // 4 * 4 * 3 = 48 members
declare const name: EventName
const parts = name.split(".") // string[]: nothing here needed 48 literal types

48 is fine. Add two more parts and it is thousands, and every comparison and every switch over it gets slower. When the compiler never needs the exact string, model it as fields ({ kind: Kind; status: Status; region: Region }) or as a brand (lesson on brands) and build the string at runtime.

isolatedDeclarations makes the previous advice a compiler rule. It requires every export to have enough annotation that its declaration file can be written from that one file alone, with no inference across modules. That is what lets tools emit .d.ts files in parallel without running the full checker. The flag exists in this tsc:

export const f = (x: number) => ({ a: x })
export function g(x: number) { return x + 1 }

With --isolatedDeclarations (and declaration on), both lines are rejected:

b.ts(1,39): error TS9013: Expression type can't be inferred with --isolatedDeclarations.
b.ts(2,39): error TS9013: Expression type can't be inferred with --isolatedDeclarations.

Fix them the way you would for speed anyway: (x: number): { a: number } => ... and g(x: number): number. The flag costs a few annotations and gives you fast declaration builds. Turn it on for library-style packages, not for every app.

When a project grows, split it. A TypeScript project can mark itself composite, and another can list it under references. tsc --build (or -b) then checks only the projects whose inputs changed, and incremental saves a .tsbuildinfo file between runs:

{
"compilerOptions": { "composite": true, "declaration": true },
"include": ["src"]
}
Terminal window
./node_modules/.bin/tsc -b

Relay could split into domain, worker and http projects. An edit in http then does not re-check domain. This is a structural change, so do it when one project is too big for Check time, not as a first step.

If Check time is a fraction of a second, leave the types alone. Readability beats a speedup you can’t measure. An interface extends is free to adopt, but a hand-written type with fifteen counters to avoid recursion is not. Optimize types that show up in a trace, and keep the simple version for everything else.

Relay’s Deps is an intersection and Paths has no depth limit, so a self-referential Node is rejected. Rewrite Deps as an interface, add the depth limit, and write the runtime twin of Paths. The tests check that the refactor accepts exactly the same things.

  • Measure first: tsc --extendedDiagnostics (Check time, Types, Instantiations) and --generateTrace <dir> for the slow spot.
  • Prefer interface X extends A, B {} to A & B for named shapes. It is cached, and it reports conflicts.
  • Annotate return types on exports. --isolatedDeclarations enforces it.
  • Give recursive types a depth limit, and watch template-literal unions multiply.
  • Use project references (composite, tsc -b) when one project is too large, not before.
  • Performance: the compiler team’s own tuning advice and diagnostics flags.
  • TypeScript 4.5: tail-recursion elimination and Awaited.