"declaration"

Generates .d.ts files with types next to the compiled JavaScript.

On this page

Example

#
JSON
{
  "compilerOptions": {
    "declaration": true,
    "outDir": "./dist"
  },
  "include": ["src"]
}

Definition and usage

#

With declaration: true, the compiler writes a .d.ts file next to every .js file. It contains only types: function signatures, interfaces, and the types of classes and constants, with no implementation.

This is essential when publishing a library to npm. The user gets working JavaScript and the types that let the editor offer suggestions and check calls. The path to the declarations is given in package.json with the types field, or the types condition in the exports field.

Related options: declarationDir writes declarations to a separate folder, emitDeclarationOnly generates only .d.ts files (when another tool builds the JavaScript), and declarationMap lets you jump in the editor from a type straight to the .ts source file.

Syntax

#
Syntax
"declaration": true

More examples

#
The source and the generated declaration
TypeScript
// src/progress.ts
export interface Progress {
  done: number
  total: number
}

export function percent(progress: Progress): number {
  return Math.round((progress.done / progress.total) * 100)
}

// dist/progress.d.ts (generated):
// export interface Progress {
//     done: number;
//     total: number;
// }
// export declare function percent(progress: Progress): number;
A library’s package.json
JSON
{
  "name": "@codeworlds/progress",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/progress.d.ts",
      "default": "./dist/progress.js"
    }
  }
}

Good practices

#
  • Applications, e.g. on Next.js or Vite, don’t need declarations. Enable declaration in libraries and in packages shared across a monorepo.
  • Write out the return types of exported functions explicitly. The declarations are then easier to read, and the isolatedDeclarations option (TypeScript 5.5) actually requires it, so that other tools can generate .d.ts without full type checking.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.