Sub topic 13
Generating .d.ts files with the declaration option
This chapter shows how tsc writes declaration files for your own code, how to read them, and which settings and mistakes affect them. It assumes you can run tsc, edit tsconfig.json, and read basic TypeScript types. It also assumes you know what a .d.ts file is from the earlier chapters on declaration files.
What the declaration option does
When declaration is true, the compiler writes a .d.ts file next to each .js file it emits. The .d.ts file keeps the type-level shape of your exports and drops everything else. Consumers of your library get types from it, and they never need your .ts source.
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src"]
}Given this source file:
// src/index.ts
export function add(a: number, b: number): number {
return a + b;
}
// dist/index.d.ts (generated by tsc with declaration: true)
export declare function add(a: number, b: number): number;The function body is gone. The declare keyword marks the line as describing something that exists elsewhere, in the matching .js file.
What ends up in the output
The compiler writes the public surface of each module. It treats the rest as implementation detail.
| Source construct | Appears in the .d.ts |
|---|---|
| Exported function | Signature only, no body |
| Exported `const` with an initializer | Type only, as `declare const` |
| Exported interface or type alias | Kept as written |
| Exported class | Members with types, no bodies |
| `private` class member | Name only, with no type |
| `#private` class member | A single `#private;` marker |
| Non-exported helper | Omitted, unless an exported declaration uses it |
| `import type` | Kept |
Inferred types are written out
You do not have to annotate everything. The compiler writes the inferred type into the declaration file.
// src/util.ts
export const config = { retries: 3, name: "api" };
export function makeId(prefix: string) {
return prefix + Date.now();
}
// dist/util.d.ts
export declare const config: {
retries: number;
name: string;
};
export declare function makeId(prefix: string): string;This is convenient, but the output depends on the inference. If you change a function body, the public type can change without any edit to the signature. Library authors often annotate exported return types so the contract is explicit and does not shift by accident.
Classes and private members
// src/counter.ts
export class Counter {
private count = 0;
#secret = 1;
increment(): number {
return ++this.count;
}
}
// dist/counter.d.ts
export declare class Counter {
private count;
#private;
increment(): number;
}The .d.ts records that private members exist. Classes with private members are compared by declaration identity, so two structurally identical classes with private fields are still not assignable to each other. The declaration file preserves that behavior.
Controlling where and what is emitted
Several options refine the behavior of declaration.
| Option | Effect |
|---|---|
| `declarationDir` | Writes `.d.ts` files to a separate directory instead of `outDir`. |
| `emitDeclarationOnly` | Writes only `.d.ts` files and no JavaScript. Use it when a bundler or another tool produces the JavaScript. |
| `declarationMap` | Writes `.d.ts.map` files so "Go to Definition" in an editor jumps to your `.ts` source. |
| `stripInternal` | Removes declarations whose JSDoc contains `@internal`. |
| `composite` | Used for project references. It turns on `declaration` automatically. |
| `isolatedDeclarations` | Requires explicit types on exports so other tools can generate `.d.ts` files without a full type check. |
A common setup pairs a bundler with tsc used only for types:
{
"compilerOptions": {
"module": "nodenext",
"strict": true,
"declaration": true,
"emitDeclarationOnly": true,
"declarationMap": true,
"declarationDir": "dist/types"
},
"include": ["src"]
}Hiding internals with stripInternal
Mark an export with an @internal JSDoc tag and enable stripInternal. The declaration file then omits it, while the JavaScript still contains it.
/** @internal */
export function debugDump(): void {
console.log("state");
}
export function publicApi(): string {
return "ok";
}The .d.ts will contain only publicApi. The tag works for exports that other files in your own package import. The .js file still exports debugDump, so this does not make the function private at runtime.
File extensions and module types
The extension of the declaration file follows the extension of the source file.
| Source | JavaScript output | Declaration output |
|---|---|---|
| `.ts` | `.js` | `.d.ts` |
| `.mts` | `.mjs` | `.d.mts` |
| `.cts` | `.cjs` | `.d.cts` |
These pairs matter under module: "nodenext". A .d.mts file is read as an ES module and a .d.cts file as CommonJS. A package that ships both formats needs a matching declaration file for each one.
Gotchas and common errors
Types that cannot be named
An exported declaration may use a type that the declaration file has no way to refer to. The compiler then reports an error such as TS2742: "The inferred type of 'x' cannot be named without a reference to '...'. This is likely not portable. A type annotation is necessary."
This usually happens when an inferred type comes from a transitive dependency that your file never imports. The fix is to add an explicit annotation, or to import the type so the declaration can name it.
import type { Request } from "express";
export function getPath(req: Request) {
return req.path;
}Here the parameter type is written explicitly and the return type is inferred as string, so the .d.ts is straightforward. Problems appear when both come from inference that crosses package boundaries.
Path aliases are not rewritten
If you use paths in tsconfig.json, the compiler resolves aliases like @app/utils while checking your code. It copies the specifier unchanged into both the .js and .d.ts output. Your consumers will see @app/utils, which they cannot resolve. Avoid aliases in published code, or run a tool that rewrites them in both file types.
Handwritten .d.ts files are not copied
If your src folder contains a .d.ts file, tsc reads it as input but does not write it to outDir. When the published types depend on that file, copy it in your build script.
Extensions in relative imports are preserved
With nodenext, you write ./user.js in the source even though the file on disk is user.ts. The emitted .d.ts keeps ./user.js. That is correct, because the declaration file sits next to a real user.js and resolves to the matching user.d.ts.
Stale output
tsc does not delete old files. If you rename or remove a source file, its old .d.ts stays in dist and can leak outdated types into your package. Clean the output directory before each build.
Checking your result
Run the build and look at the output. Then confirm the types work from a consumer's point of view.
- Run
npx tscand open the files indist. - Check that every exported name you expect is present and that no internal names leak.
- Run
npm pack --dry-runto confirm that the.d.tsfiles are included in the package. - Import the package from a small separate project with
stricton and check that the types resolve.
The last step catches problems that the build cannot, such as a missing types entry in package.json. A later chapter covers that entry.
Exercise
A project uses a bundler to produce JavaScript. You want tsc to produce only type declarations in dist/types, with source maps for editor navigation. Which options do you set, and what happens to a function marked with a JSDoc @internal tag if you also enable stripInternal?
Show answer
Set declaration: true, emitDeclarationOnly: true, declarationDir: "dist/types", and declarationMap: true. With stripInternal enabled, the function is removed from the .d.ts output. It still exists in the JavaScript the bundler produces, so it is hidden from the types only and is not private at runtime.
Exercise
You export export const config = { retries: 3 }; and tsc generates a declaration file. What does the declaration for config look like, and why might you add an explicit annotation anyway?
Show answer
The output is export declare const config: { retries: number; };, written across several lines. The type is inferred from the initializer. An explicit annotation makes the public type a deliberate contract, so changing the initializer later cannot silently change the type consumers see.