Sub topic 10
Rolling out isolatedDeclarations in an existing project
This chapter assumes you have read the earlier chapters on isolatedDeclarations and explicit annotations. It also assumes you can edit a tsconfig.json, run tsc from the command line, and know what a .d.ts file is. A monorepo helps but is not required.
Turning on isolatedDeclarations in a new package is easy, because you write annotations as you go. In a codebase with thousands of exports, the first compile can report hundreds of errors. This chapter covers how to size that work, split it into safe steps, and keep the result from regressing.
What the option asks of your code
With isolatedDeclarations enabled, tsc must be able to write each file's .d.ts by looking at that file alone. Wherever an exported declaration's type depends on inference that crosses a file boundary, the compiler reports an error and asks for an annotation.
Three properties shape the rollout:
- Only exported API surface is affected. Local variables, unexported functions, and function bodies need no changes.
- The errors are mechanical. Each one names a declaration that needs an explicit type.
- Fixing them changes source text, not runtime behavior. Type annotations are erased at emit.
The option also requires declaration or composite to be on. If neither is set, tsc reports a configuration error instead of checking your code.
Step 1: Measure the size of the job
Do not enable the option in your main tsconfig.json yet. Create an audit config next to it that extends the real one and turns the option on without emitting files.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"isolatedDeclarations": true,
"noEmit": true,
"incremental": false,
"composite": false
}
}If your main config sets composite: true or incremental: true, the overrides above stop the audit run from writing build info. Save the file as tsconfig.isolated.json, then count the errors per package:
tsc -p tsconfig.isolated.json --pretty false \
| grep -c "error TS9"The errors raised by this option have codes in the 9000 range, so the TS9 filter separates them from ordinary type errors. Run the command in each package of a monorepo and write the numbers down. They give you three things:
- An ordering for the rollout, with the smallest counts first.
- A rough effort estimate.
- A baseline to compare against when you check your progress.
Step 2: Choose the order
Packages that other packages depend on gain the most. A library that sits at the bottom of the reference graph blocks everything above it, so its declaration emit is on the critical path. Packages at the top, such as apps that nobody imports, gain little, because nothing needs their .d.ts files.
A practical order:
- Leaf libraries with a low error count. These build confidence and a fix pattern.
- Heavily imported libraries, even if the count is high. These give the largest speedup once parallel emit tools use them.
- Everything else, as time allows.
- Apps and other packages that publish no declarations, usually never.
Because the diagram fence below follows the required format, here is the rollout flow:
Step 3: Fix errors in bulk
You do not have to write every annotation by hand. TypeScript's editor support offers quick fixes for these errors, including an "Add inferred type" style action that writes the type the compiler would have inferred. In VS Code, put the cursor on the error and press the quick-fix shortcut. Fix-all actions work at file level for some of the error kinds.
The typical patterns look like this:
// Before: each of these needs work under isolatedDeclarations
export class Cache {
items = new Map<string, number>();
size() {
return this.items.size;
}
}
export const defaults = { retries: 3, name: "app" };
export const makeId = () => Math.random().toString(36).slice(2);
// After
export class Cache {
items: Map<string, number> = new Map();
size(): number {
return this.items.size;
}
}
export const defaults = { retries: 3, name: "app" };
export const makeId = (): string => Math.random().toString(36).slice(2);defaults needs no change here because every property is a simple literal that the compiler can type from this file alone. The class property needs an annotation because new Map() is a call expression, and size and makeId need return types because their types come from function bodies. The checks follow the same rule throughout: if the type can be read directly from the declaration's own syntax, no annotation is needed.
Review what the quick fix wrote
Automatic fixes write the type the compiler inferred, which is sometimes not the type you want to publish. Check these cases before you commit:
- Very long inline types. An inferred object type pasted into a signature is hard to read. Move it into a named
interfaceortypeand use the name. - Types that need imports. The fix may reference a type from another module. Make sure it is imported with
import typewhere your lint rules expect it. - Widening and narrowing. If you replace an inferred literal type with
stringornumber, the public API gets looser. If you replace a wide type with a narrow one, it gets stricter. Callers can break either way.
You can catch the last problem by comparing generated declarations before and after. Emit .d.ts files with the old config, enable the option, emit again, and run a plain diff -r on the two output folders. A clean rollout produces no differences, or only differences you can explain.
tsc -p tsconfig.json --declaration --emitDeclarationOnly --outDir /tmp/dts-before
# ...apply annotations...
tsc -p tsconfig.json --declaration --emitDeclarationOnly --outDir /tmp/dts-after
diff -r /tmp/dts-before /tmp/dts-afterStep 4: Handle the hard cases
Some errors cannot be fixed by adding a type next to the declaration. They point at constructs that need restructuring.
- Computed or spread values in exported objects. An exported object built with a spread of another object, or with computed keys, gives the compiler no way to list its properties from one file. Write the object type as an interface and annotate the variable with it.
- Exports built by calling a function.
export const config = loadConfig();needsexport const config: Config = loadConfig();, which means theConfigtype must be nameable in this file. Import or declare it. - Factory-style APIs with deep inference. Libraries that derive types from schemas or builders often export values whose types are huge. Here an explicit annotation can be long. If the type already has a name in the library, use it. If it does not, the error is a hint that the public API had an unnamed type that consumers could not refer to anyway, and naming it is worth doing.
- Declaration merging and re-exports. Plain
export { x } from "./x"is fine. The risk is inexport *combined with generated or inferred members, so check those files in the diff step.
If a particular file is too hard to convert right now, keep it out of the first phase. Move it to a separate package, or leave the package off the rollout list until it is ready. Avoid any as a shortcut. It silently degrades the types your consumers see, and the diff in the previous step will show it.
Step 5: Enable it and lock it in
When the audit count reaches zero for a package, move the options into that package's real tsconfig.json:
{
"compilerOptions": {
"composite": true,
"declaration": true,
"isolatedDeclarations": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}From this point, new code in the package gets the errors while it is being written, and the editor offers the quick fix on the spot. Make the CI type-check step run on this config so that a missing annotation fails the build.
For a package you are still converting, keep a ratchet. Store the current error count from the audit command in a file in the repository, and fail CI if the count rises above it. Lower the number each time you fix a batch. This keeps old code improving and stops new code from adding to the backlog.
#!/usr/bin/env bash
set -euo pipefail
allowed=$(cat .isolated-baseline)
actual=$(tsc -p tsconfig.isolated.json --pretty false | grep -c "error TS9" || true)
if [ "$actual" -gt "$allowed" ]; then
echo "isolatedDeclarations errors rose: $actual > $allowed"
exit 1
fiThe || true matters. grep -c exits with status 1 when it finds zero matches, and with set -e that would fail the script at exactly the moment you finish the migration.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Enabling the option in the root config first | Every package fails at once and the work is blocked | Use an audit config and convert one package at a time |
| Accepting every quick fix unreviewed | Large inline types and accidental API changes | Name the types and diff the emitted `.d.ts` files |
| Annotating with `any` to silence errors | Consumers lose type safety | Write the real type, or defer that file |
| Setting the option without `declaration` or `composite` | Configuration error | Turn on one of them |
| Converting a top-level app first | Large effort with no build benefit | Start with libraries that others depend on |
Exercise
A package has 140 isolatedDeclarations errors in the audit run. A teammate wants to enable the option in the package's tsconfig.json now and fix the errors over the next two weeks. What do you recommend instead, and how do you stop new errors from appearing meanwhile?
Show answer
Keep the option out of the real tsconfig.json and use a separate audit config (tsconfig.isolated.json) that extends it with isolatedDeclarations and noEmit. Fix the errors in batches, review each batch by diffing the emitted .d.ts files, and store the current error count in a baseline file. In CI, fail the build if the audit count rises above the baseline, and lower the baseline after each batch. When the count reaches zero, move isolatedDeclarations into the package's tsconfig.json so the normal build enforces it.
Exercise
After the quick fix, export const makeId = () => Math.random().toString(36).slice(2); becomes export const makeId = (): string => .... Why does this declaration need an annotation, while export const defaults = { retries: 3, name: "app" }; does not?
Show answer
The return type of makeId comes from analyzing the function body, which the compiler would have to do for each file just to write its declaration. That is inference beyond the declaration's own syntax. The defaults object contains only literal values, so its type can be read directly from the declaration, and no annotation is required.