Sub topic 12
Verifying the fix and keeping it fixed
This chapter assumes you can run tsc from the command line, read a tsconfig.json, and have already made at least one change from earlier chapters: trimming the program, enabling incremental, splitting with project references, or rewriting a type. Here you confirm that the change worked and put a guard in place so the slowdown does not return.
Why one timing is not evidence
A single before-and-after comparison is easy to get wrong. Compile times vary from run to run because of disk caches, other processes, CPU throttling, and Node's JIT warm-up. A change that looks like a 10% gain may be noise.
Several things also make a comparison unfair:
- Incremental state. With
incremental: true, the second run reads a.tsbuildinfofile and does less work. Comparing a cold "before" run with a warm "after" run proves nothing. - Different inputs. If the "after" run includes fewer files because you also changed
include, you are measuring two changes together. - Different TypeScript versions. Upgrading the compiler between runs changes the result on its own.
- Editor and build differences. A faster
tscrun does not mean a faster editor. They are separate measurements.
The rule is to change one thing at a time, keep everything else fixed, and measure the same way before and after.
Build a repeatable measurement
Start with the command from the baseline chapter. For a full, non-incremental measurement, turn incremental state off for the run and disable the build info file:
npx tsc --noEmit --extendedDiagnostics --incremental falseRecord these numbers from the output:
| Field | What it tells you |
|---|---|
| Files | How many files are in the program |
| Lines of TypeScript | Size of your own source |
| Lines of Declaration | Size of `.d.ts` input, mostly from `node_modules` |
| Types | How many types the checker created |
| Instantiations | How many generic instantiations it performed |
| Memory used | Peak heap use |
| Check time | Time spent in type checking |
| Total time | Whole run |
Compare the cause-level numbers, not only total time. Files, Types, and Instantiations are counts. Counts do not depend on machine load, so they are stable across runs. If a type rewrite worked, Instantiations or Types should drop. If a scope fix worked, Files should drop. Time is the outcome you care about, but the counts tell you why it changed.
Run several times and take the median
Run the command at least five times and use the median of the Check time. A short script keeps this honest:
#!/usr/bin/env bash
# measure.sh: print the Check time for five full runs
for i in 1 2 3 4 5; do
npx tsc --noEmit --incremental false --extendedDiagnostics \
| grep -E "^Check time"
doneRun it on the old code, save the output, then run it on the new code. Use git stash or a separate branch so only your change differs. Throw away nothing from the "before" file. You will want it for the commit message.
git switch main
bash measure.sh > before.txt
git switch fix/type-perf
bash measure.sh > after.txtIf the ranges overlap, you have not shown an improvement. If they do not overlap and the counts moved in the expected direction, you have.
Measure the scenarios people actually experience
Different fixes help different scenarios. Measure each one that applies.
- Cold full check. No incremental state. This is what a fresh CI machine without a cache sees.
- Warm incremental check, no changes. Run twice and time the second run. This shows the floor.
- Warm incremental check after a small edit. Change one file, then rerun. This is what a developer sees in watch mode or a pre-commit hook.
- Editor responsiveness. Open the project, wait for it to load, and measure completions and diagnostics in the slow file.
An incremental-build fix will not change scenario 1 at all. A type rewrite should change scenarios 1, 2, and 3 but may leave a warm run with no changes looking the same. Report each scenario separately so nobody concludes the fix failed because the wrong one was timed.
For scenario 3, make a real edit to a widely imported file and a leaf file. A leaf edit should be fast. A widely imported file shows how far changes propagate.
npx tsc --noEmit --incremental --extendedDiagnostics # prime the cache
echo "// touch" >> src/shared/types.ts
npx tsc --noEmit --incremental --extendedDiagnostics # measure
git checkout src/shared/types.tsConfirm the fix with a second trace
When the fix targeted a specific hot spot from the trace, check that the hot spot is gone. Generate a new trace and run the analyzer again:
npx tsc --noEmit --generateTrace traceAfter
npx @typescript/analyze-trace traceAfterCompare it with the analysis from before. The file or type that was reported as a hot spot should be absent or much shorter. If a different hot spot now leads the list, that is normal. The slowest item is always at the top of a sorted list, so after you remove one, the next one appears. Decide whether it is worth fixing by its absolute duration, not by its position.
Be careful about two outcomes:
- The hot spot moved instead of shrinking. Annotating one function can push the cost to its callers if the real expense is the type itself. Check that total Check time and Instantiations fell.
- Total time did not change but the hot spot disappeared. The slow span may have been a small share of the whole. The trace showed a real hot spot, but it was not the bottleneck.
Check that behavior did not change
A faster build is only useful if it still reports the same errors. Type rewrites can loosen or tighten checking by accident. For example, replacing an intersection with an interface changes how conflicting property types are reported: an intersection with conflicting members yields never for that property, while an interface extending conflicting types is an error at the declaration.
Before merging, confirm:
- The project still compiles with zero errors (or the same errors as before).
- Declaration output is still correct if you publish a library. Diff the
.d.tsfiles from before and after. - Your existing type tests still pass. If you have none for the rewritten types, add a few, as shown below.
// type-tests.ts: compile-time checks that fail the build if the type changes shape
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
interface User { id: string }
interface Permissions { canEdit: boolean }
interface AdminUser extends User, Permissions {}
const userKeysAreStable: Equal<keyof AdminUser, "id" | "canEdit"> = true;If someone later changes AdminUser so its keys differ, this file stops compiling. That protects the semantics of your performance fix, not only its speed.
Keep it fixed: budgets in CI
Performance regressions are rarely one big mistake. They accumulate through new dependencies, a broad include, or one more clever generic. The only reliable defense is an automated check that fails when a number crosses a line.
Use the counts, not wall-clock time, as the gate. CI machines are noisy, so a time threshold will either flake or be set so loose it catches nothing. Instantiations, Types, and Files are deterministic for a given source tree and TypeScript version.
This script extracts the numbers and compares them against a budget:
#!/usr/bin/env bash
# check-ts-budget.sh: fail if the program grows past agreed limits
set -euo pipefail
MAX_FILES=2400
MAX_INSTANTIATIONS=1800000
out=$(npx tsc --noEmit --incremental false --extendedDiagnostics)
files=$(echo "$out" | awk '/^Files:/ {print $2}')
inst=$(echo "$out" | awk '/^Instantiations:/ {print $2}')
echo "Files: $files (max $MAX_FILES)"
echo "Instantiations: $inst (max $MAX_INSTANTIATIONS)"
if [ "$files" -gt "$MAX_FILES" ]; then
echo "Program has too many files. Run --explainFiles to find out why." >&2
exit 1
fi
if [ "$inst" -gt "$MAX_INSTANTIATIONS" ]; then
echo "Instantiation count over budget. Generate a trace and run analyze-trace." >&2
exit 1
fiSet each limit about 10% above the current value. That leaves room for normal growth and still catches a jump. When a legitimate change pushes a number up, raise the limit in the same pull request so the increase is a visible, reviewed decision.
The script prints the next diagnostic step in its failure message. Whoever sees the red build then knows what to run without reading this tutorial.
Other guards
- Pin the TypeScript version. Use an exact version in
package.jsonand a lockfile. Upgrade deliberately and re-measure, because a compiler release can improve or worsen specific patterns. - Keep type checking separate from bundling. Run
tsc --noEmitas its own CI step so its time is visible and not hidden inside a build. - Cache
.tsbuildinfoin CI. Store the file between runs keyed on the lockfile and TypeScript version. A stale cache from a different compiler version is ignored, but caching still saves time when the inputs match. - Lock down the scope. Keep
includeexplicit andtypeslisted, so that adding a dependency does not silently pull in new global typings. - Review type-heavy changes. Add a note to your pull request template: if the change adds a generic utility type, a large union, or a recursive conditional type, attach the Instantiations count before and after.
{
"compilerOptions": {
"noEmit": true,
"incremental": true,
"tsBuildInfoFile": ".cache/tsconfig.tsbuildinfo",
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}Setting tsBuildInfoFile gives CI a fixed path to cache.
A decision flow for the next slowdown
When the build gets slow again, work through the same loop. It reuses everything from this tutorial.
Reverting is part of the process. A change that does not move the counts is a guess that did not pay off, and keeping it adds complexity for nothing.
Common errors when verifying
- Timing a run that included
npxdownload or startup. Install dependencies first, then time. Use./node_modules/.bin/tscif startup is noisy. - Forgetting
--noEmiton one side. Emit adds time. Use the same flags for both runs. - Comparing watch mode to a one-shot run. Watch mode keeps state in memory and is not comparable.
- Reading the editor as a build metric. The editor uses
tsserver, which does extra work such as completions and semantic diagnostics per open file. Verify editor fixes with the tsserver log from the previous chapter. - Setting a budget with no headroom. A limit equal to today's value fails on the first unrelated commit and trains the team to ignore it.
- Leaving the trace directory in the repository. Trace files are large. Add
traceDirto.gitignore.
Exercise
A teammate says their rewrite of a large intersection type into an interface "made the build 15% faster" based on one run before and one run after. List three things you would check or change before accepting that claim, and name one number from --extendedDiagnostics that would show the rewrite worked regardless of machine noise.
Show answer
Check that both runs used the same flags and the same incremental state (for example --incremental false), that the TypeScript version and the set of files did not change, and that the result holds across at least five runs using the median of Check time. Also confirm behavior is unchanged, since an interface can report conflicts differently from an intersection. The Instantiations count (or Types) is deterministic for a given source tree, so a drop there shows the rewrite reduced checker work independent of machine noise.
Exercise
Why does the CI budget script gate on Files and Instantiations instead of Total time, and what should a developer do when a legitimate change pushes a count over its limit?
Show answer
Files and Instantiations are counts that stay the same between runs on the same source and compiler version, while Total time varies with machine load and would either flake or need a limit too loose to catch regressions. When a legitimate change exceeds a limit, the developer raises the limit in the same pull request so the increase is reviewed, ideally after confirming with a trace that the growth is expected.