Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 96 ยท TypeScript in Practice

Scaling TypeScript: Project References and Build Performance

Scale TypeScript to monorepos - project references, composite and incremental builds, tsc --build, isolatedDeclarations, skipLibCheck and finding slow types.

A single tsconfig.json and one tsc --noEmit run work well for a long time. Then the codebase grows: a front end, a server, a shared library, a few internal packages. Every save type-checks all of it, CI spends minutes on files nobody touched, and one package can quietly import private files from another. At that size you need to tell TypeScript how the code is split up, so it can check each part once, reuse the results and enforce the boundaries between parts.

This lesson covers the tools for that: monorepo layouts, project references with composite and tsc --build, incremental builds and .tsbuildinfo files, the options that make per-file tools safe (isolatedModules, isolatedDeclarations), and how to measure a slow build and find the types that cause it. Our editor runs a single file with fixed options, so configuration appears as read-only code, and the runnable examples rebuild the ideas behind each feature in plain TypeScript.

Monorepos in one picture

A monorepo keeps several packages in one repository. A typical TypeScript layout looks like this:

TEXT
acme/
  package.json            workspaces: ["packages/*", "apps/*"]
  tsconfig.base.json      shared compiler options
  tsconfig.json           the "solution": references only, no files
  packages/
    utils/                tsconfig.json + src/
    core/                 references utils
    api-client/           references core and utils
  apps/
    server/               references core
    web/                  references api-client and core

Two systems cooperate here. The package manager's workspaces (npm, pnpm, Yarn or Bun) link the packages so import { slugify } from '@acme/utils' resolves to the folder next door instead of the npm registry. Project references tell TypeScript which packages depend on which, so it can check them in the right order and treat each one as a separate unit. Workspaces alone work, but then tsc re-checks every package's source each time it sees an import. References are what make large repositories fast.

Project references

Each package gets its own tsconfig.json that extends the shared options and lists the packages it depends on:

JSON
// tsconfig.base.json
{
  "compilerOptions": {
    "target": "es2023",
    "module": "nodenext",
    "strict": true,
    "skipLibCheck": true,
    "composite": true,
    "declarationMap": true,
    "sourceMap": true
  }
}
JSON
// packages/api-client/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": ["src"],
  "references": [{ "path": "../core" }, { "path": "../utils" }]
}

The root tsconfig.json is a "solution" file. It owns no source files and simply points at every project, so editors and tsc -b can find them all:

JSON
// tsconfig.json
{
  "files": [],
  "references": [
    { "path": "packages/utils" },
    { "path": "packages/core" },
    { "path": "packages/api-client" },
    { "path": "apps/server" },
    { "path": "apps/web" }
  ]
}

A referenced project must set composite: true. That one option switches on several rules at once:

  • declaration is forced on. Other projects never read a referenced project's .ts sources while building; they read its emitted .d.ts files. That is the speedup: a declaration file is a summary, much cheaper to load than the implementation.
  • Every source file must be matched by include or files. A project can't silently pull in files it doesn't own, so the boundary between packages is real.
  • rootDir defaults to the folder of the tsconfig.json, which keeps the output layout predictable.
  • incremental is on by default, so the project keeps a .tsbuildinfo file (more on that below).

declarationMap is worth adding: it makes "Go to Definition" in your editor jump to the original .ts source of another package instead of its .d.ts file.

Building with tsc --build

Plain tsc -p builds one project. tsc --build (short: tsc -b) is a small build orchestrator. Given a project, it follows the references, works out which projects are out of date, and builds them in dependency order, each one before anything that depends on it. References must not form a cycle; if utils referenced web while web (indirectly) referenced utils, there would be no valid order, and tsc -b reports an error.

Here is the core of that algorithm, a depth-first walk that emits dependencies first and detects cycles:

TypeScript Build order from project references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
tsc -b apps/web
  1. packages/utils
  2. packages/core
  3. packages/api-client
  4. apps/web
tsc -b apps/server
  1. packages/utils
  2. packages/core
  3. apps/server
error: circular references: apps/web -> packages/api-client -> packages/core -> packages/utils -> apps/web

Notice that building apps/server never touches api-client or web: you only pay for what the target depends on. The satisfies check (see The satisfies Operator) validates the workspace shape while keeping its exact keys, so show('apps/mobile') would be a compile error. Cycles are a design problem, not a configuration problem: the usual fix is to move the shared code into a lower-level package that both sides reference.

The commands you'll use day to day:

Terminal
tsc -b                  # build the solution (all referenced projects)
tsc -b apps/web         # build one app and whatever it depends on
tsc -b --verbose        # explain why each project is (or isn't) rebuilt
tsc -b --dry            # show what would be built, build nothing
tsc -b --watch          # rebuild affected projects on every save
tsc -b --clean          # delete outputs, including .tsbuildinfo files
tsc -b --force          # ignore build info and rebuild everything

Incremental builds and .tsbuildinfo

With incremental (on by default under composite), the compiler writes a .tsbuildinfo file after each build. It records a hash of every input file, the dependencies between files, and the errors found last time. On the next run, TypeScript compares hashes and re-checks only files that changed, plus the files that depend on them. If you use incremental without composite, put the file somewhere predictable with "tsBuildInfoFile" and ignore it in Git.

tsc -b adds one more shortcut between projects. When a project is rebuilt, it compares the new .d.ts output with the old one. If only function bodies changed, the declarations are identical, and downstream projects don't need to be checked again: nothing they can see has changed. This simulation follows the same rules:

TypeScript What tsc --build skips

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
1) first build
  utils: checked and emitted (no build info)
  core: checked and emitted (no build info)
  web: checked and emitted (no build info)
2) nothing changed
  utils: up to date, skipped
  core: up to date, skipped
  web: up to date, skipped
3) utils: implementation changed, signature did not
  utils: checked and emitted (sources changed)
  core: up to date, skipped
  web: up to date, skipped
4) utils: new optional parameter (the .d.ts changes)
  utils: checked and emitted (sources changed)
  core: checked and emitted (a reference changed its .d.ts)
  web: checked and emitted (a reference changed its .d.ts)

Step 3 is the everyday case: you fix a bug inside a shared function and only that package is re-checked. Step 4 changes the package's public surface, so everything that can see it is checked again. That's also a design lesson: small, stable public APIs make builds faster, because fewer edits ripple outward. The real compiler stores far more detail per file (it even re-checks only the affected files inside a project), but the decision rules are the ones you just ran.

Keep .tsbuildinfo files and dist folders out of Git, but do cache them in CI between runs (most CI systems can restore a folder by key). A warm cache turns a full check of an unchanged monorepo into a few seconds of hash comparisons.

Options that keep per-file tools honest

In large projects, tsc is usually not the tool that produces JavaScript. Vite, esbuild, SWC and Node's own type stripping compile one file at a time, without looking at other files' types (see Tooling and TypeScript with Node.js). Three options make the compiler warn about code those tools would get wrong:

  • isolatedModules reports code that can't be compiled file by file. The classic example is re-exporting a type with export { User } from './user': a per-file tool can't tell whether User is a type (to drop) or a value (to keep). Writing export type { User } fixes it. verbatimModuleSyntax, covered in Modules, is the stricter modern form and implies the same safety.
  • erasableSyntaxOnly rejects syntax that needs real code generation (enum, namespace, parameter properties), so files can be run by simply erasing types.
  • isolatedDeclarations (TypeScript 5.5+) requires that every exported declaration's type can be written into a .d.ts file without running the type checker. In practice that means explicit return types on exported functions and explicit types on exported constants whose types aren't obvious from the literal:
TypeScript
// With "isolatedDeclarations": true
export function total(prices: number[]) {
  // error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations.
  return prices.reduce((sum, price) => sum + price, 0);
}

export function totalFixed(prices: number[]): number {
  return prices.reduce((sum, price) => sum + price, 0); // fine
}

Why accept that extra typing? Because declaration emit becomes a simple per-file transformation. Build tools can produce .d.ts files in parallel and in milliseconds, and a monorepo can start building core before utils has finished type checking, since core only needs utils's declarations. Explicit return types on exported functions are a good habit anyway: the contract is written down, and an accidental change to the implementation shows up as an error inside the function instead of as a confusing error in another package. Most teams enable it in library packages first.

Measuring a slow build

Before you change anything, measure. Two flags tell you where the time goes:

  • tsc --extendedDiagnostics prints counts (files, lines, types, instantiations, memory) and the time spent in each phase: parsing, binding, checking and emitting.
  • tsc --generateTrace ./trace writes a detailed trace of the checker. Open trace.json in a browser's performance tool (or Perfetto) to see which files and which types took longest, and use the @typescript/analyze-trace package to get a ranked list of hot spots. Both flags work in the native TypeScript 7 compiler as well as in TypeScript 5 and 6.

The --extendedDiagnostics output is plain text, so it's easy to process. This program reads one run's numbers from the Input box and suggests where to look:

TypeScript Reading --extendedDiagnostics output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
Parse time   0.61s # 7%
Bind time    0.24s  3%
Check time   7.92s ################## 90%
Emit time    0.00s  0%

- Checking dominates: profile with --generateTrace and look for slow types.
- Most lines come from .d.ts files: try skipLibCheck and a narrower "types" list.
- Millions of generic instantiations: look for deep recursive or conditional types.
- A large program: split it into referenced projects and build with tsc -b.

Paste the output of your own project into the Input box and run it again. The cheap wins it points at:

  • skipLibCheck: true skips checking the contents of .d.ts files (your dependencies' declarations are still used, just not re-validated). It's in almost every recommended config.
  • A narrow types list ("types": ["node"]) stops TypeScript from loading every @types/* package in node_modules.
  • Tight include patterns keep build output, fixtures and generated files out of the program.
  • Project references split a 2,000-file program into units that are checked once and then reused.

TypeScript 7 and the native compiler

TypeScript 7 replaced the JavaScript-based compiler with a native one written in Go. The language is the same, but a full check typically runs around ten times faster, partly from native code and partly because it checks files in parallel on several threads. For many teams, that alone moves "the build is slow" off the worry list. The ideas in this lesson still matter at scale, though: references and incremental builds avoid work entirely, which beats doing the same work faster. Tools that use the old compiler's JavaScript API (some lint rules and plugins) may still need the TypeScript 6 package installed next to TypeScript 7 during the transition.

Types that slow the checker down

Sometimes one type is the problem. The checker has hard limits that protect it from types that would take forever, and hitting one is a strong hint that a type is too clever. The first limit is the size of a union. Template literal types multiply: five digits make 10 ร— 10 ร— 10 ร— 10 ร— 10 combinations.

TypeScript A union that is too big (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program doesn't run: main.ts(4,16): error TS2590: Expression produces a union type that is too complex to represent. Even below the limit, a union with tens of thousands of members makes every assignment check slow. When a type would have to list every valid string, describe the rule at runtime instead and carry the result in a branded type (see Type-Level Programming):

TypeScript A branded string instead of a giant union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
shipping to 90210
rejected 9021
rejected abcde

shipTo still only accepts checked zip codes, but the type is one small intersection instead of 100,000 literals. The second limit is recursion depth. A recursive conditional type whose recursive call is wrapped in something (here, a tuple spread) can only nest so deep:

TypeScript Recursion the checker refuses (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Range<5> is fine, but Range<500> fails with main.ts(6,14): error TS2589: Type instantiation is excessively deep and possibly infinite. The fix is to make the recursion a tail call: carry the result in an accumulator and make the recursive call the entire result of the branch. TypeScript evaluates tail-recursive conditional types in a loop and allows about 1,000 steps:

TypeScript The tail-recursive version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints [ 0, 1, 2, 3, 4 ] 499. Compiling still takes noticeably longer than the other examples, because the checker builds 500 ever-longer tuples. That's the deeper lesson: a type that compiles can still cost real seconds in every build and every keystroke in the editor.

A few habits keep the checker fast in big codebases:

  • Prefer interface ... extends to long intersections for object types. Interfaces are cached by name and their relationships are checked once; big A & B & C intersections are often re-computed.
  • Annotate return types of exported functions. The checker (and .d.ts emit) no longer has to infer and print huge anonymous types.
  • Name complex types with aliases instead of repeating large inline types; named types are easier to cache and give shorter error messages.
  • Keep clever type-level code at the edges. A recursive parser type in a widely used helper runs on every call site in the repo.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which option must a project set before other projects can reference it?

    composite: true marks a project as referenceable. It forces declaration emit, requires every file to be matched by include/files and turns on incremental builds.
  2. 2. You change only the body of an exported function in packages/utils. Its signature stays the same. What does tsc -b do with the projects that reference utils?

    Downstream projects only see utils through its declaration files. If the .d.ts output is identical, there is nothing new for them to check.
  3. 3. What does isolatedDeclarations require of export function total(prices: number[]) { ... }?

    With isolatedDeclarations, each exported declaration's type must be visible in the source, so per-file tools can emit declarations. Writing : number fixes the TS9007 error.
  4. 4. Why does type Range<N, Acc> = Acc['length'] extends N ? [] : [Acc['length'], ...Range<N, [...Acc, Acc['length']]>] fail for N = 500?

    Non-tail recursion nests one instantiation inside another. The tail-recursive version with an accumulator is evaluated in a loop and allows about 1,000 steps.
  5. 5. What does skipLibCheck skip?

    Your code still gets the types from library declarations; TypeScript just doesn't re-validate the declaration files themselves, which saves a lot of time.

Summary

  • A monorepo combines workspaces (packages import each other by name) with project references (TypeScript checks each package as a unit).
  • Referenced projects set composite: true; dependents read their .d.ts output instead of their sources. A root "solution" tsconfig.json lists every project with "files": [].
  • tsc -b builds referenced projects in dependency order, rejects cycles, and skips projects whose inputs and upstream declarations haven't changed. --verbose, --dry, --watch, --clean and --force control it.
  • incremental builds keep hashes and results in .tsbuildinfo files; cache them in CI, never commit them.
  • isolatedModules/verbatimModuleSyntax, erasableSyntaxOnly and isolatedDeclarations keep code safe for fast per-file tools and parallel declaration emit.
  • Measure with --extendedDiagnostics and --generateTrace. Cheap wins: skipLibCheck, a narrow types list, tight include patterns.
  • Giant unions (TS2590) and deep non-tail recursion (TS2589) are signs of types that are too clever; use branded types, tail recursion and simpler named types instead.

Next: Best Practices and Common Mistakes