Sub topic 3
Emitting declaration files and declaration maps
This chapter assumes you can read TypeScript, run tsc with a tsconfig.json, and know what a package.json is. It covers what declaration files are, which compiler options produce them, what goes wrong, and how to check the output. Later chapters cover how package.json points consumers at these files.
What a declaration file is
A declaration file has the extension .d.ts. It holds only the type information of a module: function signatures, interfaces, type aliases, and class shapes. It holds no runtime code.
Consumers of your library need these files for two reasons.
- The TypeScript compiler reads them to check calls into your library.
- Editors read them to give autocomplete and hover documentation.
Without declaration files, TypeScript treats your package as untyped. In strict projects the import fails with an implicit any error. In looser projects everything silently becomes any.
Turning on declaration output
Add declaration to the compiler options. With it on, tsc writes a .d.ts file next to each .js file it emits.
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}Take the small library from the earlier chapter:
// src/slugify.ts
export interface SlugOptions {
separator?: string;
}
export function slugify(input: string, options: SlugOptions = {}): string {
const separator = options.separator ?? "-";
return input
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, separator)
.replace(new RegExp(`^${separator}+|${separator}+$`, "g"), "");
}
// src/index.ts
export { slugify } from "./slugify.js";
export type { SlugOptions } from "./slugify.js";After npx tsc, the dist folder looks like this:
dist/
index.js
index.js.map
index.d.ts
index.d.ts.map
slugify.js
slugify.js.map
slugify.d.ts
slugify.d.ts.mapThe generated dist/slugify.d.ts contains only the public shape:
export interface SlugOptions {
separator?: string;
}
export declare function slugify(input: string, options?: SlugOptions): string;
//# sourceMappingURL=slugify.d.ts.mapNotice three changes from the source.
- The function body is gone.
- The default value
= {}became an optional parameter marker,options?. - The keyword
declareappears, which says "this exists at runtime, and here is its type."
The last line is a comment that points to the declaration map. It is covered below.
The options that control declaration output
Several related options exist. Knowing which does what avoids confusion.
| Option | Effect |
|---|---|
| `declaration` | Emit `.d.ts` files alongside JavaScript. |
| `declarationMap` | Emit `.d.ts.map` files that link each declaration back to the original `.ts` source. |
| `declarationDir` | Write `.d.ts` files to a different folder than `outDir`. |
| `emitDeclarationOnly` | Emit only declarations and no JavaScript. Useful when another tool produces the JavaScript. |
| `sourceMap` | Emit `.js.map` files for debugging the JavaScript. It does not affect declarations. |
| `stripInternal` | Omit declarations for members whose doc comment contains `@internal`. |
| `noEmitOnError` | Do not write any output if there are type errors. |
Most libraries only need declaration and declarationMap. Keep declarationDir unset unless you have a reason, because separating .d.ts from .js makes the paths in exports harder to reason about.
Declaration maps
A declaration map is a .d.ts.map file. It records which line in a .d.ts file came from which line in the .ts source.
The benefit is for people using your library inside an editor. When they choose "Go to Definition" on slugify, the editor normally opens the .d.ts file. With a declaration map, and with the original source present, it opens src/slugify.ts instead.
That second condition matters. The map stores a relative path to the source file, such as ../src/slugify.ts. If you publish only dist, as the files field in the example package does, that path leads nowhere. The editor falls back to the .d.ts file. The map is harmless in that case, but it adds files without adding value.
You have two choices.
- Publish
srctoo, by adding"src"tofiles. Go to Definition then works for consumers, and the package gets larger. - Do not publish the maps. Set
declarationMaptofalse, or exclude*.d.ts.mapfrom the package.
Declaration maps are most valuable inside a monorepo, where packages link to each other through the workspace and the source is always present. For a public package on npm, choice 2 is common and entirely acceptable.
Why the output differs from the input: inference
TypeScript writes the types it infers into the declaration. Take a function with no return type annotation:
export function makeId(prefix: string) {
return `${prefix}-${Date.now()}`;
}The emitted declaration is:
export declare function makeId(prefix: string): string;This works, but it ties your public API to whatever the compiler infers. A small change in the body can change the public type without you noticing. For exported functions in a library, write return types explicitly. The compiler then checks the body against your promise, and the declaration file stays stable.
The "cannot be named" errors
With declaration on, the compiler must be able to write out every type in your public API. Sometimes it cannot. A typical error looks like this:
error TS2742: The inferred type of 'client' cannot be named without a reference
to '../node_modules/some-dep/dist/types'. This is likely not portable. A type
annotation is necessary.Another is TS4058 or TS4023, which say that an exported item "has or is using name X from external module but cannot be named."
These errors happen when an exported value has an inferred type that comes from a file the declaration cannot import by a stable path. The fix is nearly always the same: annotate the export with an explicit type and import that type properly.
import type { Client } from "some-dep";
export const client: Client = createClient();This is also a reminder that your public types may pull in other packages. A later chapter covers how to declare those dependencies correctly.
Types versus values in re-exports
Under isolatedModules and verbatimModuleSyntax, re-exporting a type needs export type. The example index.ts does this:
export { slugify } from "./slugify.js";
export type { SlugOptions } from "./slugify.js";export type is erased from the JavaScript output and kept in the declaration output. If you write export { SlugOptions } for an interface under these settings, the compiler reports an error, because it cannot tell whether a runtime value exists.
Checking the output
Do not assume the declarations are right because the build passed. Inspect them.
npx tsc
cat dist/index.d.ts
npm pack --dry-runLook for these things.
- Every public name appears in
dist/index.d.ts. - No declaration refers to a path outside the package, such as
../../node_modules. - Relative imports inside
.d.tsfiles end in.js, matching the source, so Node-style resolution works for consumers. - Types you meant to keep private are absent.
The flow from source to files that a consumer uses is shown below.
Common mistakes
- Forgetting
declaration. The build succeeds and the package publishes, but consumers get no types. Check for.d.tsfiles indistevery time. - Declarations outside the published folder. If
declarationDirpoints somewhere not listed infiles, the types never ship. - Including tests in the build. Test files under
srcproduce.d.tsfiles and bloat the package. Exclude them intsconfig.jsonor use a separate config for builds. - Stale output.
tscdoes not delete old files. A renamed module leaves its old.d.tsindist. Clean before building, for example with aprebuildscript that removesdist. - Relying on inferred return types. The public API shifts without warning.
- Wrong extension on relative imports. Under
NodeNext, a relative import must include the.jsextension, even though the source file is.ts.
Where declaration output fits in the whole package
Emitting declarations is only the first half of shipping types. The second half is telling consumers where to find them. The types condition in exports, and the types field for older tools, point at dist/index.d.ts. If these two halves disagree, TypeScript reports that it cannot find declarations even though the file exists.
Exercise
You publish a package with "files": ["dist"] and declarationMap: true. A user reports that "Go to Definition" on your function opens dist/slugify.d.ts and not your TypeScript source. Why does this happen, and what are two ways to fix it?
Show answer
The declaration map stores a relative path such as ../src/slugify.ts. Because only dist is published, that file does not exist in the installed package, so the editor falls back to the .d.ts file. Fix it by either publishing src as well (add "src" to files), or setting inlineSources: true so the source text is embedded in the map. Alternatively, drop the maps if you do not need this feature.
Exercise
A source file exports export function count(items: string[]) { return items.length > 0 ? items.length : null; }. What declaration does tsc emit, and why should you change the source?
Show answer
It emits export declare function count(items: string[]): number | null;. The return type was inferred from the body, so any change to the body can change the public type unnoticed. Write the return type explicitly, : number | null, so the compiler checks the body against it.