← TypeScript

Advanced · 9 of 12 · 15 min read

Declaration files

What a .d.ts is for, how declare differs from a definition, and the three ways to add types to a library that has none.

  • Declaration files

A .d.ts file is types with no implementation. It is how a compiled library describes itself, how an untyped one gets described from outside, and how global things that exist at runtime become visible to the compiler.

What they look like

// math.d.ts
export declare function add(a: number, b: number): number;
export declare const VERSION: string;
export interface Options { precision?: number }
export declare class Calculator {
  constructor(options?: Options);
  add(a: number, b: number): number;
}

No bodies, no initialisers, no emitted output. The compiler reads this as the public surface of a module whose implementation it will never see, and add is typed at every call site in the program.

Generating them for your own library is a flag rather than a chore:

{
  "compilerOptions": {
    "declaration": true,
    "declarationMap": true,
    "emitDeclarationOnly": false,
    "outDir": "dist"
  }
}

declaration writes a .d.ts beside each .js; declarationMap adds a source map so a consumer pressing “go to definition” lands in your TypeScript source rather than in the generated types.

Three ways to type an untyped package

Approach Where it lives Good for
@types/<pkg> from DefinitelyTyped node_modules/@types anything popular
A local .d.ts in your project src/types/*.d.ts small or internal packages
declare module "pkg" with any one line unblocking a build today
// src/types/legacy-chart.d.ts
declare module "legacy-chart" {
  export interface ChartOptions {
    width: number;
    height: number;
    data: readonly number[];
  }

  export default function render(element: HTMLElement, options: ChartOptions): void;
}

Partial is fine and usually right: declare the handful of exports you actually call, and add more when you use more. The alternative at the bottom of the table is the escape hatch:

// Unblocks the build, and turns off every check at the boundary.
declare module "legacy-chart";

Everything imported from it is any. Acceptable as a marked, temporary step; a permanent hole if it is left in.

declare global

For things that exist on the global object at runtime:

// src/types/global.d.ts
export {};

declare global {
  interface Window {
    analytics?: { track(event: string): void };
    __APP_VERSION__: string;
  }

  var featureFlags: Record<string, boolean>;
}

Two details that cause most of the trouble here. First, export {} makes the file a module, which is what lets declare global mean “augment the global scope” — in a script file the whole thing is already global and the block is redundant or an error. Second, a global variable must be declared with var: let and const do not create properties on the global object, and the compiler models that faithfully.

declare global {
  var cache: Map<string, unknown>;
}

// Usable anywhere, no import:
globalThis.cache ??= new Map();
console.log(cache.size);

Module augmentation

Adding to a type that a library already declares:

import "express";

declare module "express" {
  interface Request {
    user?: { id: string; roles: readonly string[] };
  }
}

// Now `request.user` is typed everywhere in the project.
export {};

The import is load-bearing: without it, declare module "express" replaces the module’s types with a brand-new ambient declaration instead of augmenting them — and every real export disappears. The augmentation itself works because interfaces merge, so the new member joins the library’s own Request.

The same shape covers a plugin adding to a framework:

import "vitest";

declare module "vitest" {
  interface Assertion<T> {
    toBeWithin(min: number, max: number): T;
  }
}
export {};

Declare the matcher, implement it at runtime, and the two halves are connected by nothing but your diligence — which is the standing caveat for everything in this lecture.

Asset and environment declarations

The two .d.ts files almost every front-end project has:

// assets.d.ts
declare module "*.svg" {
  const url: string;
  export default url;
}

declare module "*.module.css" {
  const classes: Readonly<Record<string, string>>;
  export default classes;
}
// env.d.ts
interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  readonly VITE_FEATURE_X?: "true" | "false";
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

The first makes a bundler’s non-JavaScript imports type-check; the second turns environment variables from string | undefined guesswork into a named contract. Both are declarations about a runtime the compiler cannot see.

Triple-slash directives

The pre-module way of referring to other declarations, still seen at the top of generated files:

/// <reference types="node" />
/// <reference lib="dom" />
/// <reference path="./other.d.ts" />
export {};

types pulls in an @types package, lib pulls in a built-in library, path includes another file. In application code prefer compilerOptions.types and compilerOptions.lib in the tsconfig, which are visible in one place rather than scattered across files. The one case where the directive is still right is a published .d.ts that genuinely depends on @types/node.

declare outside a .d.ts

The keyword works in a .ts file too, and means the same thing — “exists, not emitted”:

declare const BUILD_ID: string;        // injected by the bundler
declare function gtag(...args: unknown[]): void;  // from a script tag

console.log(BUILD_ID);
gtag("event", "page_view");

That is the right tool for a value a bundler defines or a third-party script attaches. It is also how a class property that a framework assigns gets declared without an initialiser.

Nothing checks it

The point worth leaving with:

declare function add(a: number, b: number): string;  // wrong, and nobody minds

const result = add(1, 2);
console.log(result.toUpperCase());  // compiles; throws at runtime

A declaration file is a claim. If it disagrees with the JavaScript it describes, the compiler believes the declaration and the program fails at runtime with a type error the type system promised could not happen. That is why @types packages have versions tied to library versions, and why a hand-written declaration should be kept to the surface you actually use.

Common mistakes

declare module "pkg" without importing it first

Mistake. Augmenting a library’s Request or Assertion in a file with no imports. Why it fails. The file is a script, so the block declares a new ambient module and shadows the real one. Every genuine export becomes an error. What to do instead. import "pkg"; at the top, or export {} plus a type-only import.

let or const in declare global

Mistake. declare global { const flags: Flags }. Why it fails. Only var declarations become properties of the global object, and the compiler models that — the identifier resolves but globalThis.flags does not. What to do instead. var in the declaration, however wrong it looks.

Leaving the one-line escape hatch in

Mistake. declare module "some-lib"; shipped to main. Why it fails. Every import from that module is any, so the whole boundary is unchecked — silently, and forever. What to do instead. Declare the two or three functions you call. It takes minutes and it is the part that actually gets used.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

What is a .d.ts file for?

A package has no types. Where do you look before writing a .d.ts yourself?

What does module augmentation let you do?

Practise Declaration files →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.