Sub topic 1
Where the time goes: the phases of a tsc run
When tsc feels slow, the first useful question is which part of the run is slow. The compiler does several different jobs in order, and each job slows down for different reasons. Reading a trace or rewriting a type before you know which job dominates wastes effort. This chapter gives you the working model of a tsc run that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you can do the following:
- Write TypeScript with interfaces, generics, and union types.
- Read a
tsconfig.jsonand runtscfrom the command line. - Use
npmandnpxto run a locally installed tool.
You don't need to know how the compiler is implemented. The chapter describes it at the level you need for diagnosis.
The pipeline at a glance
A single tsc invocation turns your source files into diagnostics (errors) and, optionally, output files. It does this in five stages:
- Program creation.
tscreadstsconfig.json, works out which files belong to the program, and resolves everyimportand type reference to a file on disk. - Parse. Each file's text becomes a syntax tree.
- Bind. The compiler creates symbols, which are named declarations, and links them to scopes.
- Check. The type checker computes types and reports errors.
- Emit. The compiler writes
.js,.d.ts, and source map files.
Parse and bind work on text and declarations. They scale roughly with the amount of code in the program, and they are usually quick. Check is the only stage whose cost depends on what your types mean, so it is where most "mysterious" slowness lives. Still, you should confirm that rather than assume it.
Program creation, parse, and bind
Program creation and resolution
Before any parsing happens, tsc has to know which files exist. It starts from the root files, which come from files, include, and exclude in tsconfig.json. It then follows every import, /// <reference> directive, and implicit type package to find more files. Each import goes through module resolution, which checks many candidate paths on disk. It looks for .ts, .tsx, and .d.ts files, package.json fields such as exports and types, and node_modules folders up the directory tree.
Slowness here usually comes from one of three things:
- Too many files, for example
includeglobs that pull in build output, test fixtures, or generated code. - Too many type packages, because every package under
node_modules/@typesis loaded as a global by default unlesstypesis set. - Slow disk or network file systems, where thousands of small reads add up.
The next chapters show how to see exactly which files are in your program and why. For now, keep in mind that the program includes your dependencies' declaration files as well as your own code, and often those files are the larger share.
Parse
Parsing turns each file's text into a syntax tree. Its cost is proportional to the total lines the program reads. Parsing is mostly linear and mostly cheap. Parse time grows when the program is large because it includes many .d.ts files from node_modules, not because your own code is complex. A very large generated file, such as a 50,000-line API client, is another way to make parse time visible.
Bind
Binding walks each syntax tree and creates a symbol for every declaration. It then connects those symbols to the scopes they live in. A symbol is the compiler's record that "the name User in this scope refers to these declarations". Interfaces that are declared in several places merge at this stage because their declarations land on the same symbol. Bind time scales with the number of declarations and is almost always the smallest slice of a run.
The check phase
Checking is where the compiler computes types and verifies that your code is valid. It is lazy and driven by use. The checker does not compute every type up front. When it needs the type of an expression, it computes it, caches the result, and moves on. That has two consequences for diagnosis:
- A complicated type that no code uses is cheap, because it is never computed.
- A moderately complicated type used in thousands of places can be expensive, because each use may need instantiations (concrete versions of a generic type) and comparisons that are not already cached.
Here is a small example. This recursive type is legal and compiles, but it makes the checker do work proportional to the length of the tuple at each use:
type Join<T extends string[], D extends string> =
T extends [infer F extends string, ...infer R extends string[]]
? R extends []
? F
: `${F}${D}${Join<R, D>}`
: "";
type Path = Join<["api", "v1", "users", "list"], "/">;
const path: Path = "api/v1/users/list";
console.log(path);For four elements the cost is trivial. The cost rises with element count, with nesting depth, and with how many distinct instantiations the program creates. Later chapters show how to recognize this pattern and how to rewrite it.
Checking also covers the work of comparing types for assignability. When you pass an argument to a function, assign an object to a variable, or return a value, the checker asks whether one type is assignable to another. Large unions, large intersections, and deeply nested object types make each comparison costlier. The checker caches results, so the number of cache entries is a useful size signal, and --extendedDiagnostics reports it.
Check is the phase where the cost per line of code varies the most. Two projects with the same line count can have check times that differ by a factor of ten.
Emit
Emit transforms the checked syntax trees into JavaScript, then optionally writes declaration files (.d.ts) and source maps. Transformation is mostly linear in code size.
Declaration emit can be a hidden source of cost. To write a .d.ts file the compiler must print the type of every exported value. If you leave an exported function's return type unannotated, the compiler has to infer the type and then print it out in full. For a large inferred type, that printing is slow and the output is huge. A later chapter covers the fix, which is explicit annotations.
If you run with --noEmit, there is no emit work, and the emit time reads as zero. This is the right mode for a baseline, because it isolates the stages that produce diagnostics. If your real build emits, measure that as well. Emit has its own cost, and a bundler or a separate transpiler may already handle JavaScript output.
The editor runs the same stages differently
Your editor does not shell out to tsc. It talks to a long-running process called tsserver, which hosts the TypeScript language service. The service uses the same parser, binder, and checker, but it works differently:
- It keeps the program in memory and updates it as you type, so parse and bind work is repeated only for changed files.
- It checks on demand. Completions, hover text, and go-to-definition ask the checker about a single position. The editor requests error diagnostics for the files you have open.
- It runs while you wait. A command that takes two seconds in a terminal build is tolerable, but a two-second completion list feels broken.
So a project can have an acceptable tsc time and still have a slow editor. The cause may be one expensive type in a file you edit often, or a very large program held in memory. A later chapter covers tsserver logs. For now, treat "slow in CI" and "slow in the editor" as separate symptoms that share the same pipeline.
Mapping symptoms to phases
This table lists the typical stage behind each symptom. It gives you a starting hypothesis to test with measurements. It is not a diagnosis.
| Symptom | Likely stage | What to look at first |
|---|---|---|
| Slow even on a tiny change, huge file count | Program creation, parse | Files included, `include` globs, `types` |
| Slow on the first run, fast after caching | All stages | Incremental builds |
| One file takes much longer to check than others | Check | Types used in that file |
| Check time grows faster than the code does | Check | Large unions, intersections, recursive types |
| `.d.ts` output is very large or emit is slow | Emit | Unannotated exported functions |
| Terminal build is fine, editor lags | Check, in `tsserver` | `tsserver` log, files open in the editor |
A first look at the numbers
You can see the per-stage times with one command. This is the baseline measurement that the next chapter explains in detail:
npx tsc --noEmit --extendedDiagnosticsThe output has two groups of lines. The first group counts the work: files, lines per file type, identifiers, symbols, types, and instantiations. The second group lists timings. This is trimmed example output, and your numbers will differ:
Files: 412
Lines of Library: 38920
Lines of Definitions: 141306
Lines of TypeScript: 62110
Identifiers: 228904
Symbols: 171540
Types: 64210
Instantiations: 390125
Memory used: 412380K
I/O Read time: 0.21s
Parse time: 1.02s
ResolveModule time: 0.34s
Program time: 1.96s
Bind time: 0.48s
Check time: 6.85s
Emit time: 0.00s
Total time: 9.29sYou can read three things from this sample:
- Check time is about 74% of the total, so checking is the stage to investigate.
- "Lines of Definitions" is more than twice "Lines of TypeScript". Most of the program is declaration files, which suggests looking at scope and dependencies as well.
- Emit time is zero because of
--noEmit.
Program time is not a separate phase of work. It is the combined time for reading files, parsing them, and resolving modules, so it overlaps the lines above it.
Common mistakes when reading phase times
- Optimizing the wrong stage. Shaving 100 ms off bind time cannot fix a build where checking takes 40 seconds. Always find the largest stage first.
- Blaming your own code for dependency cost. If most lines are definitions, the cost may come from
node_modulestypes. Changing your own types will not help. - Comparing runs on different machines or under load. Timings vary with CPU, disk caching, and other processes. Run the same command a few times on the same machine and compare like with like.
- Forgetting that checking is lazy. A slow check means some code uses an expensive type. The declaration of that type is not necessarily where the time is attributed. Traces, covered later, show where the time goes.
- Treating one number as the whole story. Types, instantiations, and memory move together. A big jump in instantiations with similar line counts is a strong hint of an expensive generic type.
Where this fits in the tutorial
The rest of the tutorial follows the pipeline. You will measure a baseline, then reduce what the program includes, then reuse work between runs. After that you will record a trace of the checker and rewrite the types it points to. Each step targets one stage, so the model in this chapter tells you which step to try first.
Exercise
A project's tsc --noEmit --extendedDiagnostics output shows Parse time 0.9s, Bind time 0.4s, Check time 31.2s, and Emit time 0.00s. A teammate suggests removing a few large files from include to speed things up. Which stage would that mainly affect, and is it the best first step? What would you do instead?
Show answer
Removing files mainly reduces program creation, parse, and bind work, which total about 1.3 seconds here, so even a large cut saves little. (Fewer files could also reduce check work, but the numbers don't show that.) Check time is about 96% of the run, so the next step is to find what makes checking slow. Compare the counts for types, instantiations, and the assignability cache against similar projects, then generate a trace and look for expensive types. Emit is zero only because of --noEmit, so measure an emitting build separately if you ship one.