Sub topic 7
Recording what the checker does with --generateTrace
This chapter assumes you have run tsc --extendedDiagnostics and know which phase (parse, bind, check, emit) dominates your build. It also assumes you can read a tsconfig.json, and that you know what --listFilesOnly and --explainFiles tell you about program scope. If the check phase is the slow one and the file list looks sane, the next question is which files, expressions, and types the checker spends its time on. --generateTrace records that.
What the flag does
--generateTrace <dir> makes tsc write a timeline of its own work into a directory. The checker records start and end times for the units of work it performs, such as checking a source file, a variable declaration, or a relation between two types. It also records a catalog of every type it created.
npx tsc --noEmit --generateTrace traceDirThe directory is created if it doesn't exist. After the run it contains at least two files:
| File | Contents | Use |
|---|---|---|
| `trace.json` | Timed events in the Chrome trace event format | Shows when and for how long each piece of work ran |
| `types.json` | One entry per type the checker created | Turns type ids from the trace into readable descriptions and source locations |
The two files are meant to be read together. Events in trace.json refer to types by numeric id, and types.json says what each id means.
Taking a trace you can trust
Tracing adds overhead, and the trace files can reach hundreds of megabytes on a large project. A few habits keep the data useful.
- Trace a single project. Run
tsc -p path/to/tsconfig.json --generateTrace dir. Atsc --buildover many referenced projects does not give you one coherent timeline. Trace the slow project directly. - Avoid incremental reuse. With
incrementalon,tscmay skip re-checking files that haven't changed, so the trace shows only the work that was redone. Delete the.tsbuildinfofile, or pass--incremental false, so the trace covers a full check. - Use
--noEmit. If emit isn't the problem, leaving it out keeps the trace focused on checking. - Compare relative numbers. Durations in a traced run are inflated. Use the trace to rank hot spots, and use your
--extendedDiagnosticsbaseline for absolute time. - Keep the trace out of version control. Write it to a directory that is git-ignored, or to a temporary path.
rm -f tsconfig.tsbuildinfo
npx tsc -p tsconfig.json --noEmit --incremental false --generateTrace traceDir
ls -lh traceDirThe exact name of your .tsbuildinfo file depends on your tsBuildInfoFile or outDir settings. If you aren't sure where it is, --incremental false on the command line is enough.
The shape of trace.json
trace.json is a JSON array of event objects. This is the format that Chrome's tracing tools read. The fields you will meet most often are these:
name: the kind of work, for examplecheckSourceFile.cat: the category, which groups events by phase, such asparse,bind,check,checkTypes, oremit.ph: the event type.Xis a complete event that carries its owndur.BandEmark the beginning and end of a span.ts: the start time, in microseconds.dur: the duration in microseconds, present on complete events.args: details specific to the event, such as a filepath, source positionsposandend, or the ids of types being compared.
Events nest. A checkSourceFile event contains the events for the statements and expressions inside that file, and those can contain events for type relation checks. When you view the trace visually, this nesting appears as stacked bars. A long bar with nothing stacked under it is slow in itself. A long bar with one dominant child tells you to look at the child.
Event names worth recognizing
You don't need to memorize the full list. These show up repeatedly in slow projects:
| Event name | What it measures |
|---|---|
| `createProgram` | Resolving and loading all files, including module resolution |
| `checkSourceFile` | Total checking time for one file |
| `checkExpression` | Checking one expression, with its source position |
| `checkVariableDeclaration` | Checking a declaration, which includes inferring its type |
| `checkDeferredNode` | Function bodies and similar nodes the checker postpones |
| `structuredTypeRelatedTo` | Comparing two object, union, or intersection types |
| `getVariancesWorker` | Computing how a generic type's parameters vary |
The exact set varies between TypeScript versions, so inspect your own trace for names rather than assuming this table is complete.
The shape of types.json
types.json is an array of objects, one per type created during the run. Each has an id. Depending on what kind of type it is, it can also carry:
display: a printed form of the type, when the checker could produce one cheaply.symbolNameorintrinsicName: the name of the symbol or built-in type.firstDeclaration: an object withpath,start, andend, pointing at source.unionTypesorintersectionTypes: the ids of the constituent types.conditionalCheckType,aliasTypeArguments, and similar fields for more specialized types.recursionId: a marker that groups types produced by one recursive type definition.
When a structuredTypeRelatedTo event says sourceId: 4182, targetId: 90311, types.json tells you what those two types are and where they were declared. That is the step that turns "something was slow" into "this intersection, in this file, compared against that interface".
Reading the trace by hand
You can load trace.json into a trace viewer. Chrome's chrome://tracing works, and so does the Perfetto UI. Open the file, zoom into the longest bars, and click an event to see its args. This is good for getting a feel for the shape of the work. For a large project it is slow, because the browser has to load a very large file.
A small script gets you to the same starting point faster. This one lists the slowest files by checkSourceFile time. Save it as top-files.mjs.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const dir = process.argv[2];
if (!dir) {
console.error("usage: node top-files.mjs <traceDir>");
process.exit(1);
}
const events = JSON.parse(readFileSync(join(dir, "trace.json"), "utf8"));
const files = events
.filter(
(e) =>
e.name === "checkSourceFile" &&
typeof e.dur === "number" &&
e.args &&
e.args.path
)
.map((e) => ({ path: e.args.path, ms: e.dur / 1000 }))
.sort((a, b) => b.ms - a.ms)
.slice(0, 10);
for (const f of files) {
console.log(`${f.ms.toFixed(1).padStart(9)} ms ${f.path}`);
}Run it with node top-files.mjs traceDir. If it prints nothing, your TypeScript version may record this event as separate B and E entries instead of one X entry. Check the raw events with grep -m 3 checkSourceFile traceDir/trace.json and adjust the filter.
Once you have a slow file, a second script can resolve type ids from that file's relation events. This one reads types.json and prints the entry for each id you pass.
import { readFileSync } from "node:fs";
import { join } from "node:path";
const [dir, ...ids] = process.argv.slice(2);
if (!dir || ids.length === 0) {
console.error("usage: node lookup-types.mjs <traceDir> <id> [<id> ...]");
process.exit(1);
}
const types = JSON.parse(readFileSync(join(dir, "types.json"), "utf8"));
const byId = new Map(types.map((t) => [t.id, t]));
for (const raw of ids) {
const t = byId.get(Number(raw));
if (!t) {
console.log(`${raw}: not found`);
continue;
}
const where = t.firstDeclaration
? `${t.firstDeclaration.path}:${t.firstDeclaration.start.line}`
: "no declaration";
const label = t.display ?? t.symbolName ?? t.intrinsicName ?? "(unnamed)";
console.log(`${t.id}: ${label}\n ${where}`);
}The start of firstDeclaration is an object with line and character in current versions. If your version prints undefined, print the whole firstDeclaration object to see its layout.
The workflow
The next chapter automates the "rank and resolve" step with @typescript/analyze-trace. Knowing the raw format still pays off, because the tool's output is a summary of these same events, and you will sometimes need to look past the summary.
Common mistakes
- Tracing an incremental run. The trace looks fast and shows few files. You are looking at the changed files only, not the cost of a full check.
- Treating durations as absolute. A 4-second event in a traced run does not mean 4 seconds in your normal build. Rank, then verify with a real before and after measurement.
- Blaming the biggest bar.
checkSourceFilefor a file includes the cost of checking types that file merely uses. If file A imports a very expensive type from file B, the time may show up in A's bars, while the type is declared in B. ThefirstDeclarationentries intypes.jsonpoint at the type's home. - Ignoring one-time costs. The first file to use a heavy library type pays to build it. Later files reuse it. A trace that blames one early file can be showing a shared cost, so check whether the same type appears across many files before you rewrite one.
- Loading a huge file into a browser. If the viewer stalls, filter with a script first, or analyze the trace with a tool.
Summary of what you now have
After one traced run you have a timeline of the checker's work in trace.json, a catalog of types in types.json, and a way to rank files by checking time. You haven't yet identified the cause. That is the job of the analysis step, where long events are matched to specific type patterns.
Exercise
You run npx tsc --noEmit --generateTrace traceDir on a project that has "incremental": true and an existing .tsbuildinfo from yesterday's build. The trace shows only three files being checked, and the total is far below your baseline. What went wrong, and how do you fix it?
Show answer
The incremental build reused the saved state and re-checked only the files that changed, so the trace covers a partial check and underreports the real cost. Delete the .tsbuildinfo file, or add --incremental false, then trace again so the whole program is checked.
Exercise
A structuredTypeRelatedTo event in trace.json has args containing sourceId: 4182 and targetId: 90311. How do you find out which types these are and where they come from?
Show answer
Open types.json and find the entries whose id equals 4182 and 90311. Read their display, symbolName, or intrinsicName for the type's name, and firstDeclaration for the file path and position where it was declared. The lookup-types.mjs script does this lookup.