~/hackweb.dev
TypeScript Declaration Files
Quiz
...

TypeScript Declaration Files

beginner · updated Tue Sep 08 2026Contribute

Master .d.ts files and type declarations for JavaScript libraries.

TypeScript Declaration Files

Declaration files (.d.ts) provide type information for JavaScript code without implementations.

Basic Structure

A declaration file describes the public API of a module:

// logger.d.ts
export function log(message: string): void;
export function error(message: string, code: number): void;
export const DEFAULT_LEVEL: string;

Remember: Declaration files only have type signatures — no implementations.

Global Declarations

Global declarations make types available everywhere without imports:

// global.d.ts
declare const MY_API_KEY: string;
declare function showNotification(message: string): void;

interface Window {
  myCustomProperty: string;
}

When to use: For browser globals, environment variables, or global utilities.

Module Declarations

Declare types for JavaScript modules without type definitions:

declare module "math-utils" {
  export function add(a: number, b: number): number;
  export function subtract(a: number, b: number): number;
  export const PI: number;
}

@types Packages

Install community-maintained type definitions from DefinitelyTyped:

npm install --save-dev @types/node
npm install --save-dev @types/express
npm install --save-dev @types/react

Tip: Prefer @types packages over writing custom declarations.

Declaration Merging

TypeScript merges multiple declarations of the same name:

// Both declarations merge into one module
declare module "utils" {
  function format(value: string): string;
}

declare module "utils" {
  function parse(value: string): string;
}

import { format, parse } from "utils";

Migrating JavaScript to TypeScript

Write a .d.ts file alongside existing JS code:

// legacy.js
function processUser(user) {
  return `${user.name} (${user.email})`;
}
module.exports = { processUser };
// legacy.d.ts
export function processUser(user: { name: string; email: string }): string;

Best Practices

  • Use @types packages when available
  • Keep declarations minimal — only describe the public API
  • Use interfaces over types for object shapes that might be extended
  • Generate declarations with tsc --declaration for your own libraries
  • Test that declarations match the actual implementation

Common Mistakes

  • Forgetting to declare global types causes undefined variable errors
  • Adding implementations to .d.ts files — they should only have types
  • Not installing @types packages causes implicit any errors
  • Over-declaring — only declare what the library actually exports