Sub topic 4
Declaration files, declaration maps, and output directories
This chapter assumes you can read a tsconfig.json, know what target, strict, and outDir do, and have run tsc from the command line. It also assumes you have seen the composite option introduced in the previous chapter. Here we look at the files a composite project writes to disk and why project references depend on them.
Why emitted declarations matter
In a repository with one tsconfig, the compiler reads every .ts file and checks them together. With project references, a project that depends on another does not re-read the other project's source. It reads the other project's emitted .d.ts files, which are the declaration files that describe the public types of each module without any implementation.
This is where much of the speedup comes from. The compiler parses a small .d.ts file instead of type-checking the whole source of every dependency. It also means the correctness of your build depends on where those files are written and on whether they exist. Three settings control that: declaration, declarationMap, and the output directory options.
Declaration files
A .d.ts file contains type information only. For the greet module from our example:
export function greet(name: string): string {
return `Hello, ${name}!`;
}the compiler emits two files, greet.js and greet.d.ts. The declaration file looks like this:
export declare function greet(name: string): string;The function body is gone. A consuming project only needs the signature to type-check calls.
You do not need to set declaration yourself in a composite project. Setting composite: true changes the default of declaration to true, and it also turns on incremental. Setting declaration: false explicitly in a composite project is an error.
Declaration emit can fail where plain checking passes
To write a .d.ts file, the compiler must be able to spell every exported type. Code that type-checks fine can fail at declaration emit when an exported value has an inferred type that refers to something the compiler cannot name in the output. You typically see errors such as TS2742 ("The inferred type of 'x' cannot be named without a reference to ...") or TS4058.
The usual fix is to write an explicit type annotation on the exported symbol, or to import the needed type so that it can be named.
import type { Config } from "./config.js";
// An explicit return type gives the declaration emitter a name to write down.
export function loadConfig(): Config {
return { retries: 3 };
}Explicit annotations on exported functions also make the public surface of a project easier to review.
Declaration maps
A declaration map is a .d.ts.map file written next to each .d.ts file when you enable declarationMap. It records how each position in the declaration file corresponds to a position in the original .ts source. It is the same idea as a source map for JavaScript, but for types.
Without it, "Go to definition" on greet in the app project can land in dist/greet.d.ts, a generated file you should not edit. With the map, the editor can jump to src/greet.ts, the real definition.
The core project's configuration from this tutorial already enables it:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"declarationMap": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}declarationMap is separate from sourceMap. sourceMap produces .js.map files used by debuggers and stack traces. declarationMap produces .d.ts.map files used by editors. You can turn either on without the other.
The declaration file ends with a comment pointing at its map, which is how tools find it:
export declare function greet(name: string): string;
//# sourceMappingURL=greet.d.ts.mapOutput directories
Three options decide where files land.
| Option | Controls | Default when unset |
|---|---|---|
| `outDir` | Where `.js` files are written, and `.d.ts` files too unless `declarationDir` is set | Next to each source file |
| `rootDir` | The source directory whose folder structure is mirrored under `outDir` | In a composite project, the folder containing the tsconfig |
| `declarationDir` | Where `.d.ts` and `.d.ts.map` files are written | Same as `outDir` |
The compiler mirrors the structure under rootDir inside outDir. With rootDir: "src" and outDir: "dist", the file src/util/text.ts becomes dist/util/text.js and dist/util/text.d.ts. If you leave out rootDir, a composite project uses the tsconfig's own folder. The src segment then appears in the output as dist/src/util/text.js, which surprises people. Setting rootDir explicitly avoids that.
After building core, the layout looks like this:
packages/core/
tsconfig.json
src/
greet.ts
dist/
greet.js
greet.d.ts
greet.d.ts.map
tsconfig.tsbuildinfoThe tsconfig.tsbuildinfo file stores what the compiler needs for incremental builds. A later chapter covers it in detail. Add dist to .gitignore, because these files are generated.
Splitting declarations from JavaScript
Use declarationDir when you want types in a separate place from the runtime output:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"declarationMap": true,
"rootDir": "src",
"outDir": "dist/js",
"declarationDir": "dist/types"
},
"include": ["src"]
}A consuming project works out where to find core's declarations from this configuration, so the split is safe for references. If your bundler produces the JavaScript, you can go further and have tsc write only declarations:
{
"compilerOptions": {
"composite": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}With emitDeclarationOnly, tsc still type-checks and still writes .d.ts files and .tsbuildinfo, which is everything project references need.
How a consumer finds the output
The app project imports core by relative path to the source file:
import { greet } from "../../core/src/greet.js";
console.log(greet("project references"));Because packages/app/tsconfig.json lists core under references, the compiler does not parse core/src/greet.ts here. It takes the path of the imported source file and computes the matching output file from core's rootDir and outDir (or declarationDir). So packages/core/src/greet.ts is redirected to packages/core/dist/greet.d.ts, and that file is read instead.
This redirect explains the most common failure of this chapter. If the output file does not exist, the compiler reports an error like this:
error TS6305: Output file '/repo/packages/core/dist/greet.d.ts' has not been built from source file '/repo/packages/core/src/greet.ts'.It means core has not been built, or was built with different outDir settings than its current tsconfig states. Run tsc --build on the app project, or on the root solution config, and core is built first.
Edge cases to know
- Changing
outDirinvalidates old output. The consumer looks in the new location, so rebuild after any change tooutDir,rootDir, ordeclarationDir. includemust cover every file. A composite project requires that every source file be matched byincludeorfiles. A file that is imported but not matched produces an error such as TS6307 ("File ... is not listed within the file list of project"). Declaration emit for it would otherwise be impossible.- Do not point two projects at the same
outDir. One project's output can overwrite or confuse the other's, and clean builds will delete files you wanted. - Hand-written
.d.tsfiles are not copied. The compiler emits declarations but does not copy.d.tsfiles fromsrcintodist. If a source filesrc/types/globals.d.tsis needed by consumers, you must copy it yourself or restructure it into a.tsmodule. - Edits to
distare lost. The files are regenerated whenever their source changes.
Exercise
A project has rootDir: "src" and outDir: "build". Where are the JavaScript file and the declaration map written for src/util/text.ts if declaration and declarationMap are on and declarationDir is not set?
Show answer
The JavaScript file is build/util/text.js. The declaration file is build/util/text.d.ts and the map is build/util/text.d.ts.map. Without declarationDir, declarations follow outDir, and the src prefix is dropped because it is the rootDir.
Exercise
The app project fails with TS6305: Output file '.../core/dist/greet.d.ts' has not been built from source file '.../core/src/greet.ts'. Name two likely causes and the fix.
Show answer
Core has never been built, or it was built before its outDir, rootDir, or declarationDir changed, so the declaration file is not where the compiler now expects it. Run tsc --build on app or on the root solution config. That builds core first and writes the declarations to the current location.