Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท tsconfig: Language, Modules and Emit Options

TypeScript declaration and declarationDir options

Reference for declaration and declarationDir: generate .d.ts files for a library, how inferred types are written out, and the errors that block emit.

declaration makes the compiler write a .d.ts file next to each compiled .js file. A declaration file holds only the types of the public API, with no implementation. Libraries publish them so that other TypeScript projects get autocomplete and type-checking without reading your source.

declarationDir puts those .d.ts files in a different folder than the JavaScript. composite projects turn declaration on automatically. If you ship an npm package that other TypeScript users import, you almost certainly want this option.

JSON
{ "compilerOptions": { "declaration": true, "declarationDir": "types" } }

Try it

The compiler writes a declaration by looking at the types of every exported name, including types it infers. This example uses typeof to show what would appear in a .d.ts.

TypeScript What a declaration would contain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript A hand-written declaration for the same API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

JSON
{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "dist/types",
    "declarationMap": true
  }
}
Name Description
declaration true or false. Emits .d.ts for each input file.
declarationDir Folder for the .d.ts files. Defaults to outDir, or next to the source.
declarationMap Also emits .d.ts.map files so "Go to definition" jumps to the .ts source.

Usage notes

  • A file that exports something whose type cannot be named (for example a type from a private package) fails with errors such as TS2742 or TS4023; add an explicit return type or import the type.
  • Add explicit return types on exported functions: it keeps the .d.ts small and stable, and is required by isolatedDeclarations.
  • Only exported things appear; local helpers are omitted.
  • stripInternal removes members marked with /** @internal */ from the output.
  • declaration works with emitDeclarationOnly when another tool produces the JavaScript.
  • Point types (or exports conditions) in package.json at the generated entry file.