Sub topic 12
Generating declarations in parallel with other tools
This chapter assumes you have read the chapters on isolatedDeclarations and --noCheck. You should know that isolatedDeclarations requires explicit annotations on exported declarations, and that tsc --noCheck skips type checking. You should also be comfortable with npm scripts and a basic monorepo layout.
Why other tools can emit declarations now
A .d.ts file describes the public surface of a module. Before TypeScript 5.5, the only reliable way to produce one was to run the full TypeScript type checker. If you wrote export const config = loadConfig();, something had to resolve loadConfig, which may live in another file, and work out its return type. That work needs the whole program.
isolatedDeclarations removes that need. Every exported declaration must carry enough written type information that its declaration can be derived from the syntax of one file. Nothing has to be inferred across files.
This has a practical consequence. A tool that only parses syntax can now produce correct declarations. It does not need the TypeScript checker, and it can process each file independently. Independent files can be processed on separate threads, or by a native-code tool that is much faster than tsc at parsing.
What an isolated emitter does
An isolated emitter reads one file and writes one .d.ts file. For each exported declaration, it copies the annotations you wrote and drops the implementation. For the function below, it keeps the signature and discards the body.
export interface Point {
x: number;
y: number;
}
export function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}The emitted declaration is:
export interface Point {
x: number;
y: number;
}
export declare function distance(a: Point, b: Point): number;The emitter never needs to know what Math.hypot returns. It cannot know what Point means beyond its text either, and it does not have to. It copies the type syntax you wrote. This is why the annotation rules are strict. If a type were missing, the emitter would have to guess, so it reports an error instead.
Which tools can do this
Several tools can emit declarations from a single file without a type checker. Check each one's current documentation, because these projects change quickly and their option names and APIs have shifted between releases.
| Tool | Kind | How you typically use it |
|---|---|---|
| `tsc` with `--noCheck` | The TypeScript compiler | Emits declarations without checking. It still builds the whole program, so it is single-process. |
| oxc (`oxc-transform`) | Native-code toolchain | Has an isolated declaration transform, callable from Node. |
| swc (`@swc/core`) | Native-code compiler | Has an isolated declaration API, callable from Node. |
| Bundler plugins | Plugins for Rolldown, Vite, esbuild-style bundlers | Call one of the emitters above, then optionally bundle the `.d.ts` files. |
The first row is not truly parallel across files. It is still useful because it skips type checking, which is the largest share of build time in most projects. The other rows work per file, so they can use every CPU core.
All of these tools face the same limit. They accept only code that satisfies isolatedDeclarations. If your project has isolatedDeclarations enabled and tsc reports no errors, an isolated emitter should be able to process every file. If a tool reports an error for a file that tsc accepts, treat it as a bug or a version mismatch in the tool.
A split build: check and emit at the same time
The most useful pattern is to run two jobs at once. One job type-checks and emits nothing. The other emits declarations and does no checking. Neither waits for the other.
A tsconfig.json for the library enables the guarantee:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"declaration": true,
"isolatedDeclarations": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}The npm scripts then split the work:
{
"scripts": {
"typecheck": "tsc --noEmit -p .",
"build:dts": "tsc --noCheck --declaration --emitDeclarationOnly -p .",
"build:js": "node scripts/build-js.mjs",
"build": "npm run typecheck & npm run build:dts & npm run build:js & wait"
}
}Here build:js stands for whatever transpiler you already use for JavaScript output. Running these jobs in the background with & and wait works in bash and sh. On Windows, use a cross-platform runner such as npm-run-all with its --parallel option.
One caveat applies to the build script above. With & and wait, the shell returns the exit status of the last command only, so a failed typecheck can be hidden. In CI, collect each job's exit code, as in this script:
#!/usr/bin/env bash
set -u
npm run typecheck & pid_check=$!
npm run build:dts & pid_dts=$!
npm run build:js & pid_js=$!
status=0
wait "$pid_check" || status=1
wait "$pid_dts" || status=1
wait "$pid_js" || status=1
exit "$status"This waits for each job separately, so one failure makes the whole script fail while the other jobs still finish and print their output.
Using an isolated emitter inside your own script
When you use a native emitter from Node, the pattern is the same regardless of the tool. You list the source files, call the emitter once per file, and write each result next to its output path. Because each file is independent, you can run the calls concurrently.
This script shows the structure. It takes the emitter as a function, so you can plug in the API of whichever tool you chose. It uses only Node built-ins.
import { readFile, writeFile, mkdir, readdir } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
async function listTs(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await listTs(full)));
} else if (entry.name.endsWith(".ts") && !entry.name.endsWith(".d.ts")) {
files.push(full);
}
}
return files;
}
// emit(filename, sourceText) must return { code, errors }.
// Adapt this call to the API of your chosen emitter.
export async function emitAll(srcDir, outDir, emit) {
const files = await listTs(srcDir);
let failed = false;
await Promise.all(
files.map(async (file) => {
const text = await readFile(file, "utf8");
const { code, errors } = await emit(file, text);
if (errors && errors.length > 0) {
failed = true;
console.error(`${file}: ${errors.length} error(s)`);
return;
}
const target = join(outDir, relative(srcDir, file)).replace(/\.ts$/, ".d.ts");
await mkdir(dirname(target), { recursive: true });
await writeFile(target, code);
})
);
if (failed) process.exitCode = 1;
}Promise.all overlaps the file reads and writes. Whether the emit step itself uses several CPU cores depends on the tool. Native emitters usually do the work off the main JavaScript thread, and a pure JavaScript emitter would need worker threads to get real parallelism.
Where this approach differs from `tsc --build`
Project references and tsc --build already avoid re-checking a library whose inputs did not change. Isolated emitters solve a different problem, so you should know which one you have.
| Situation | Better fit |
|---|---|
| Few changes between builds, slow cold builds in CI | Cache `.tsbuildinfo` and use `tsc --build` |
| Many packages, each waiting for its dependency's `.d.ts` | Isolated emit, so dependents can start without a full upstream check |
| A single large package with slow declaration emit | `--noCheck` plus a separate `--noEmit` check |
| You cannot add the required annotations | Stay with `tsc` for declarations |
In a reference graph, a package normally waits for its dependencies to finish type checking, because the dependent reads their .d.ts files. With isolated emit, the .d.ts files exist long before checking finishes. The dependent's checking can start earlier. Checking is still required, and it does the same work, but the order of work changes and more of it overlaps.
Failure modes and edge cases
- Different output from
tsc. Isolated emitters may format output differently, for example in whitespace or in how they order members. Do not compare declaration files byte for byte. Compare them by type-checking a consumer project against each output. - Features outside the guarantee. Declaration bundling, path alias rewriting, and
/// <reference>handling are separate concerns. Emitters differ on whether they support them. If your published package needs a single bundled.d.ts, check that your tool does it. - Version drift. A native emitter bundles its own parser. When you upgrade TypeScript to a new syntax release, the emitter may reject new syntax until it is updated. Pin versions and upgrade them together.
- Silent acceptance of errors. An emitter that does not report type errors will produce a
.d.tsfile from code that does not compile. This is the same trap as--noCheck. - Declaration maps. If you rely on
declarationMapfor go-to-definition into source, confirm that your emitter generates maps and that they point at the right files.
Checklist before switching
tsc --noEmitpasses withisolatedDeclarations: true.- A separate
tsc --noEmitjob is a required gate in CI. - A consumer project type-checks against the emitted
distfiles. - Tool and TypeScript versions are pinned.
- You measured both builds with
--extendedDiagnosticsfortscand with wall-clock time for the whole pipeline, and the new one is faster.
Exercise
Your CI runs tsc --noCheck --declaration --emitDeclarationOnly and a native isolated emitter in parallel with no other jobs. The pipeline is green, but a consumer reports that a published function returns the wrong type. What is missing from the pipeline, and why did it stay green?
Show answer
A type-checking job such as tsc --noEmit is missing. Both the --noCheck run and the isolated emitter write declarations without checking whether the code is correct, so they succeed even when the source has type errors. Adding tsc --noEmit as a required job, and a consumer project that type-checks against dist, would have caught the error.
Exercise
Why can an isolated emitter process each file on its own thread, while classic declaration emit cannot?
Show answer
With isolatedDeclarations, every exported declaration is annotated well enough that its declaration comes from the syntax of its own file. The emitter does not need to infer types from other files. Classic emit may need the type of an expression defined elsewhere, so it needs the full program.