Course contentsShow
← TypeScript
Lesson 1148 of 1,79627. Declaration FilesFree lesson

Publishing Declaration Files

Include .d.ts files in your package with types field in package.json to distribute types with your library.

Publishing Declaration Files

What you'll learn: How to include .d.ts files in your package and configure package.json so TypeScript users automatically get type information when they install your library.

Why Publish Declaration Files?

When you publish a JavaScript library to npm, TypeScript users won't have type information unless you provide it. Publishing declaration files alongside your code gives consumers autocomplete, type safety, and inline documentation without requiring a separate @types package.

Think of it like shipping assembly instructions with furniture — your library works without them, but users have a much better experience when they know exactly what pieces they're working with.

The Two-Step Setup

Step 1: Generate declaration files

In your tsconfig.json, enable declaration generation:

{
  "compilerOptions": {
    "declaration": true,
    "outDir": "./dist"
  }
}

When you compile with tsc, TypeScript creates .d.ts files alongside your JavaScript output.

Step 2: Point to declarations in package.json

Add a types (or typings) field that points to your main declaration file:

{
  "name": "my-library",
  "version": "1.0.0",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts"
}

Now when someone installs your package, TypeScript automatically discovers the types.

What Gets Published

Make sure your .d.ts files are included when you publish. Check your files array in package.json:

{
  "files": [
    "dist/**/*.js",
    "dist/**/*.d.ts"
  ]
}

Without this, npm might exclude your declaration files even if you generated them.

Key Takeaway: Set "declaration": true in tsconfig.json and add "types": "./dist/index.d.ts" to package.json — this bundles type information with your library so TypeScript users get full type safety automatically.