Skip to Content
TypeScriptTypeScript3.3 Declaration Files

Declaration Files 📜

.d.ts files describe the shape of JS libraries so editors know their APIs—think of them as subtitles for runtime code.

When You Need Them 🤔

  • Shipping a JS library but want TypeScript consumers to get types.
  • Wrapping third-party globals (window.payments?).
  • Augmenting modules that lack a type definition.

Anatomy of .d.ts 🧬

// types/logger.d.ts export interface LoggerOptions { level?: "info" | "warn" | "error"; } export function createLogger(options?: LoggerOptions): Logger;
  • No implementations—only signatures.
  • Use declare keyword for ambient/global definitions.
declare global { interface Window { analytics?: AnalyticsClient; } }

Remember to reference the file (via types array or include).

Module Augmentation ➕

Add fields to existing modules.

declare module "express" { interface Request { user?: { id: string }; } }
  • Place inside .d.ts that lives somewhere TypeScript can find.
  • Great for extending frameworks (Express, Fastify, etc.).

Publishing Types 📦

  1. Include .d.ts files in npm package.
  2. Point package.json to them:
{ "types": "dist/index.d.ts" }
  1. Generate automatically with tsc --emitDeclarationOnly.

DefinitelyTyped / @types 🎁

  • Massive community repo of .d.ts files.
  • Install via npm i -D @types/lodash (package name matches library).
  • For scoped packages: @types/react-router or @types/express-serve-static-core.

Analogy: DefinitelyTyped is a public library of subtitles someone already wrote for you.

Tips ✅

  • Keep declarations versioned alongside runtime code.
  • Use declare namespace for global script builds.
  • Add tests with tsd or typescript-test to ensure declarations match behavior.
  • Avoid ambient globals when modules will do—namespaces can collide.

Good declarations make your library feel first-class in any editor. ✨

Last updated on