Codectionary / Developer documentation / TypeScript

Declaration Files (.d.ts)

Declaration files contain only type information, no actual implementation - they describe the shape of existing JavaScript code so TypeScript can type-check against it. This is how you get autocomplete and type safety for plain JavaScript libraries, and how your own TypeScript library can ship types alongside its compiled JavaScript output.

Syntax

declare module "name" { }
declare function fn(): type;

Examples

Declaring Types for an Untyped Module

Adding type information for a JavaScript library that has none.

// my-library.d.ts
declare module "my-untyped-library" {
  export function doSomething(value: string): number;
  export const version: string;
}

// Now "my-untyped-library" can be imported with full type checking,
// even though the actual library is plain, untyped JavaScript

Declaring Global Variables

Describing a global variable injected by an external script, like an analytics library.

// globals.d.ts
declare const analytics: {
  track: (event: string, data?: object) => void;
};

// Now "analytics" can be used anywhere in the project with type checking,
// even though it is never explicitly imported

Best practices

  • Check DefinitelyTyped (the @types/ npm scope) first before writing your own declaration file - many popular untyped libraries already have community-maintained types
  • Ship a .d.ts file alongside your own published TypeScript library so consumers get full autocomplete and type checking without needing separate type packages
  • Keep hand-written declaration files minimal and focused only on what you actually use from the untyped library, rather than fully typing its entire API upfront
  • Use declare global carefully and sparingly for genuinely global values (like a script-injected variable) - overuse can make type origins confusing

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation