Sub topic 1
Where TypeScript build time goes
Before you can make a TypeScript build faster, you need to know what the compiler does and which of those steps costs the most. This chapter lays out the stages of a tsc run, shows which ones usually dominate, and shows how the two features in this tutorial, incremental and isolatedDeclarations, target specific stages. Later chapters cover measuring, configuring, and adopting each feature in detail.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic TypeScript, including generics and inferred types.
- Run
tscfrom the command line and edit atsconfig.json. - Recognize a
.d.tsdeclaration file and know it describes the types of a module without its implementation. - Read a monorepo layout. Familiarity with npm workspaces helps but is not required.
You do not need to know compiler internals. The chapter builds the model you need.
The four stages of a tsc run
A tsc invocation reads your tsconfig.json, builds a program, checks it, and writes output. The work splits into four stages that run in order for the whole program.
- Parse. The compiler finds every file the program needs, reads it, and turns the text into a syntax tree (an AST). It also resolves each
importto a file on disk and loads the standard library files such aslib.es2022.d.ts. - Bind. The binder walks each syntax tree and creates symbols. A symbol is the compiler's record that a name, such as
config, is declared somewhere. The binder also builds scopes and the control-flow graph used for narrowing. Binding does not look at types. - Check. The type checker computes the type of expressions and declarations and reports errors. It works lazily, resolving a type when something asks for it. Checking one file can pull in type information from many other files.
- Emit. The compiler writes JavaScript, source maps, and, if
declarationis on,.d.tsfiles.
Parse and bind are cheap compared with the other two on most projects. The two stages that usually take the most time are check and emit, and emit becomes expensive mainly when it needs information from the checker.
Why checking costs the most
The checker does the semantic work of the compiler: assignability between types, generic instantiation, overload resolution, conditional types, and control-flow narrowing. Three properties make it expensive.
- It is whole-program. To know the type of
xina.ts, the checker may need the declaration of a function inb.ts, whose type depends on a generic inc.ts. A change in one file can therefore change the result for others. - It is lazy but cumulative. The checker resolves types on demand and caches them, but each file you add to the program adds more declarations to resolve. Type-heavy code, such as deeply nested conditional types, large unions, and heavily instantiated generics, can dominate the check time of a project with few files.
- It runs for every file in the program. That includes files in
node_modulesand your own.d.tsfiles. Library declaration files are parsed and bound even when you do not edit them. TheskipLibCheckoption skips checking.d.tsfiles, which saves time but also hides errors inside them.
A project with 2,000 files of simple code can check faster than one with 200 files full of complex generics. File count alone does not predict check time.
Why emit is not always cheap
Emitting JavaScript is mostly syntax work. TypeScript removes type annotations and rewrites newer syntax for your target. Each file can be transformed from its own syntax tree, with little type information. That is why tools like esbuild, swc, and Babel can strip types very quickly without a type checker.
Emitting declaration files is different. A .d.ts file must state the type of every exported name. When you write the type yourself, the compiler can copy it. When you leave it out, the compiler must infer it, and inference uses the checker.
Here are two files.
// config.ts
export interface Config {
retries: number;
endpoint: string;
}
export function loadConfig() {
return { retries: 3, endpoint: "https://example.com" };
}// settings.ts
import { loadConfig } from "./config";
export const settings = loadConfig();To write settings.d.ts, the compiler must know the type of settings. That type comes from the return type of loadConfig, which was never written down. So the compiler must resolve the import, infer the return type from the function body, and print it as a type. The output is roughly the following.
export declare const settings: {
retries: number;
endpoint: string;
};No single file contains that answer. It is derived across files, and that dependence is why declaration emit cannot be done one file at a time today. The chapter on isolatedDeclarations returns to this.
What the program includes
The parse stage decides how much work the later stages have. The program contains every file matched by include (or files), plus everything those files import, directly or indirectly, plus the libraries and ambient type packages.
Two settings control a large part of this.
libandtarget. These choose which standard library declaration files load. A broadlibsuch as["ES2022", "DOM"]parses the DOM declarations, which are large. A Node-only project that does not need the DOM can leave"DOM"out.types. By default, every package undernode_modules/@typesis included globally. Setting"types": ["node"]limits the program to the packages you name. This reduces parse and check work and prevents accidental global conflicts.
A tsconfig that narrows the program looks like this.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"lib": ["ES2022"],
"types": ["node"],
"strict": true,
"outDir": "./dist"
},
"include": ["src"],
"exclude": ["dist", "node_modules"]
}Without "types", a stray @types/jest or @types/mocha in a nested dependency is pulled into your build even if you never use it.
A first look at where the time goes
The compiler can report its own phase times. The flag is --extendedDiagnostics, and a later chapter covers it fully. For now, run it once to see the shape of a build.
tsc -p . --extendedDiagnosticsThe output has two groups of lines. The first describes the size of the program: files, lines of library, definition, and TypeScript code, plus counts of identifiers, symbols, types, and instantiations. The second lists times. This example is illustrative, not from a real project.
Files: 412
Lines of Library: 38000
Lines of Definitions: 210000
Lines of TypeScript: 52000
Instantiations: 1900000
Parse time: 0.90s
Bind time: 0.35s
Check time: 6.20s
Emit time: 1.10s
Total time: 8.70sRead it this way:
- If Check time is the largest number, as here, then skipping unchanged files (
incremental) and avoiding repeated checking across packages (project references) will help most. - If Lines of Definitions is far larger than Lines of TypeScript, much of the work is reading
.d.tsfiles, many of them fromnode_modules. Narrowingtypesand enablingskipLibCheckare the first things to try. - A very high Instantiations count points at type-level complexity in your own code or a dependency. No build setting fixes that. You need to simplify the types.
- If Emit time is large with
declarationon, declaration emit is doing inference work. This is whereisolatedDeclarationspays off.
Which feature attacks which cost
The two features in this tutorial do not speed up the compiler itself. They reduce how often, or how much, a stage runs.
| Cost | Feature | How it helps |
|---|---|---|
| Re-checking files that did not change | `incremental` and `.tsbuildinfo` | Saves the program state from the last run and reuses results for unaffected files. |
| Re-checking a whole dependency package each time | Composite projects and `tsc --build` | A package is built once. Its dependents read its `.d.ts` output instead of its source. |
| Declaration emit that needs the checker | `isolatedDeclarations` | Requires explicit types on exports, so a declaration file can be written from one file alone. |
| Checking and emit tied together | `--noCheck` | Emits output without checking, so checking can run as a separate step. |
| Repeating all of this on every CI run | Caching `.tsbuildinfo` and outputs | Restores prior build state so CI behaves like a second local run. |
Each of these has a cost. Incremental state takes disk space and can be stale or corrupt. Project references add configuration and require composite, which imposes constraints on include, rootDir, and declaration. isolatedDeclarations requires you to write type annotations you could previously omit. Later chapters treat each trade-off in turn.
Common mistakes when reasoning about build time
- Optimizing without a baseline. Running with a single timing, or only the total, hides which stage is slow. Record the phase times before you change anything.
- Blaming file count. As noted above, type complexity often matters more than the number of files.
- Confusing a slow editor with a slow build. The language service in your editor does the same checking but is long-lived and incremental in its own way. A slow CLI build and a slow editor can have different causes.
- Assuming a bundler checks types. Tools such as esbuild and swc strip types without checking them. A fast bundler build does not mean your types are valid, so a separate
tsc --noEmitis still needed. - Treating
skipLibCheckas free. It saves time but stops the compiler from catching conflicts between declaration files. Turn it on knowingly.
Exercise
A project reports Parse time 0.8s, Bind time 0.3s, Check time 9.5s, Emit time 3.4s, and has declaration set to true. Which two stages are the best targets, and which feature from this chapter's table would you try for each?
Show answer
The check stage is the largest, so try incremental (and project references if the code is split into packages) to avoid re-checking unchanged files. Emit is the second largest and declaration is on, so declaration emit is probably doing inference through the checker. isolatedDeclarations addresses that by requiring explicit annotations on exports so declarations can be generated file by file. Parse and bind are small and not worth tuning first.
Exercise
Why can esbuild emit JavaScript for a TypeScript file without a type checker, but tsc cannot generally write a .d.ts file for an unannotated export const settings = loadConfig(); without one?
Show answer
JavaScript output only needs types removed, which depends on the syntax of that single file. The declaration file must state the type of settings. That type comes from the inferred return type of loadConfig in another file, so the compiler needs the checker to resolve imports and infer the type.