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.
Measure with --extendedDiagnostics
Section titled “Measure with --extendedDiagnostics”The tsc in this course is TypeScript 7, the native compiler. Its help lists the diagnostics flags:
./node_modules/.bin/tsc --help --all### Compiler Diagnostics--diagnostics--extendedDiagnostics--generateCpuProfile--generateTraceGenerates an event trace and a list of types.--traceResolution--extendedDiagnostics exists in this build. Run it on the project and read the counters:
./node_modules/.bin/tsc -p src/exercises --extendedDiagnosticsFiles: 327Lines: 157080Identifiers: 121642Symbols: 111823Types: 15641Instantiations: 24674Memory used: 84636KMemory allocs: 283611Config time: 0.006sParse time: 0.043sBind time: 0.012sCheck time: 0.024sEmit time: 0.000sTotal time: 0.089sThese 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
Instantiationsby half is a real win even if the clock is noisy. - Files and Lines include
libandnode_modulesdeclarations. A hugeFilescount points at imports ortypespulling 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.
Find the slow type with --generateTrace
Section titled “Find the slow type with --generateTrace”When Check time is high, ask which file or type is responsible. --generateTrace takes an output directory and
exists in this build:
./node_modules/.bin/tsc -p src/exercises --noEmit --generateTrace ./tracels tracelegend.jsontrace.jsontypes_0.jsontypes_1.jsontypes_2.jsontypes_3.jsontrace.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.
Interfaces over intersections
Section titled “Interfaces over intersections”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 & LoggerPortinterface 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.
Annotate exported return types
Section titled “Annotate exported return types”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 limitconst 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: EventNameconst parts = name.split(".") // string[]: nothing here needed 48 literal types48 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.
Isolated declarations
Section titled “Isolated declarations”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.
Project references, briefly
Section titled “Project references, briefly”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"]}./node_modules/.bin/tsc -bRelay 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.
When not to optimize
Section titled “When not to optimize”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.
Exercise
Section titled “Exercise”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 {}toA & Bfor named shapes. It is cached, and it reports conflicts. - Annotate return types on exports.
--isolatedDeclarationsenforces 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.
Further reading
Section titled “Further reading”- Performance: the compiler team’s own tuning advice and diagnostics flags.
- TypeScript 4.5: tail-recursion elimination and
Awaited.