Declaration Files: Teaching TypeScript About the World

Declaration Files: Teaching TypeScript About the World in TypeScript: An electronics workshop builds boards around sealed components: an op-amp, a sensor…

The Analogy: The Datasheet for a Sealed Electronic Component

An electronics workshop builds boards around sealed components: an op-amp, a sensor module, a voltage regulator, each a black plastic package you cannot open and whose silicon you will never see. Every such part ships with a datasheet, a document that contains none of the actual silicon, only a description of the part: which pin does what, what each input expects, what each output produces, and the limits within which the part behaves. The component works whether or not you have the datasheet in your hand; the paper exists purely so an engineer can wire to the part correctly without seeing inside it. A .d.ts declaration file is exactly that datasheet. It contains no implementation, no function bodies, nothing that survives compilation, and its only job is to describe the shape of something whose real code lives elsewhere so the compiler can check your use of it.

The datasheet describes things the workshop itself did not manufacture, and this is the point of it. It might cover a third-party chip bought in, a signal that another board injects onto a shared bus, or an interface the bench equipment already handles physically. In the same way a .d.ts describes a plain JavaScript library that shipped with no types, a global variable a script tag drops onto the page, a non-code import that a bundler resolves, or the process environment. The keyword declare is the datasheet's voice throughout: it says "this exists somewhere else, take the specification as given," and there is no body attached because there is no code to attach, only the contract that the real thing is promised to honour.

Datasheets are extended rather than rewritten. A manufacturer issues an errata sheet that adds a pin or a note to the original spec without reprinting the whole document, and an engineer can pencil in an annotation that clearly refers back to the original part. TypeScript interfaces are open in precisely this way: declare the same interface name twice and the members merge instead of clashing, which is the one thing an interface can do that a type alias cannot, and it is how you add a field to someone else's library type without forking their code. The crucial rule is that an addendum must clearly reference the original datasheet or it is read as an entirely new, replacement spec. In code, a .d.ts with no import or export is a global script, and a declare module "x" inside it replaces that module's types; adding any top-level import or export turns the file into a module and switches the same declare module into augmentation mode.

The failure mode is that a datasheet is a claim, not a measurement. If the sheet states that a pin outputs five volts but the actual part delivers three, every board built to the sheet is wrong, and nothing in the paper itself will ever detect the discrepancy, because the paper does not measure the part. A .d.ts that declares an environment variable as a required string does nothing to make it present at runtime; if the variable is missing you get undefined sitting behind a type that insists it is a string, the same boundary problem seen elsewhere. The compiler trusts a declaration blindly, so an inaccurate one is worse than none at all, since it hands you false confidence. The discipline is to describe only the surface you actually use, keep every claim honest, and separately validate at runtime anything the datasheet cannot itself guarantee.


Syntax or Core Structure

The foundational behaviour behind declaration files is declaration merging: declare the same interface name more than once and TypeScript combines the members into a single interface. This is what lets a later declaration add to an earlier one rather than conflict with it.

// src/merge.ts
interface User { id: number; }
interface User { name: string; }

// The two declarations merge into { id: number; name: string }
const u: User = { id: 1, name: "ada" };

console.log(u.id);
console.log(u.name);
console.log(u.id + u.name.length);

Output:

1
ada
4

The two interface User declarations do not clash; TypeScript merges them so User has both id and name, and the object literal must supply both or it fails to compile. At runtime the value carries id of 1 and name of "ada", so the first two lines print those, and the last adds u.id to u.name.length, the length of "ada", giving 1 + 3 = 4. A .d.ts file uses the same openness, plus the declare keyword, to describe code that has no types of its own:

// types/legacy-chart.d.ts -- a datasheet for an untyped library
declare module "legacy-chart" {
    export interface ChartOptions {
        width?: number;
        height?: number;
    }
    export function render(opts: ChartOptions): number;
}

This file has no runtime effect at all; it exists only so that import { render } from "legacy-chart" type-checks. declare means the implementation lives elsewhere and the compiler should take the contract on trust.


Technical Depth: Augmentation, the Module Rule, and Env Vars

Merging is the mechanism behind module augmentation, the act of adding to a library's types from outside. Whether a declare module augments or replaces hinges on one rule about imports, and environment typing is the place the whole idea most often goes wrong.

Augmentation is merging pointed at a library

The same merging that combined two local interfaces can add a field to a type another module already exports, which is how a middleware attaches data to a request object without the library knowing.

// src/augment.ts
interface Config { port: number; }
interface Config { retries: number; }

// Merged into { port: number; retries: number }
const config: Config = { port: 8080, retries: 3 };

console.log(config.port);
console.log(config.retries);
console.log(config.port + config.retries);

Output:

8080
3
8083

Two Config declarations merge exactly as User did, so the object must carry both port and retries. The values print 8080 and 3, and their sum is 8083. Aimed at a third-party module rather than a local interface, this same merging is augmentation, and the syntax looks like this:

// types/express.d.ts -- an errata sheet for someone else's datasheet
import "express";

declare module "express-serve-static-core" {
    interface Request {
        currentUser?: { id: number };
    }
}

The one rule that decides augment versus replace

The import "express" line at the top is essential and easy to miss. A .d.ts file with no import or export is a global script, and declare module "x" inside it replaces the module's types wholesale. Adding any top-level import or export turns the file into a module, which switches declare module into augmentation mode, merging your members with the library's rather than overwriting them. This single distinction, module versus global script, is the most common reason an augmentation "does nothing" or, worse, silently blanks out a library's real types.

Environment variables are a claim, not a check

Typing process.env through augmentation is convenient and dangerous in equal measure, because the declaration is trusted without being verified. The honest approach validates at runtime and returns a typed value.

// src/env.ts
interface Settings {
    port: number;
    timeout: number;
}

function required(env: Record<string, string | undefined>, key: string): string {
    const value = env[key];
    if (value === undefined) {
        throw new Error("missing env: " + key);
    }
    return value;
}

function loadSettings(env: Record<string, string | undefined>): Settings {
    return {
        port: Number(required(env, "PORT")),
        timeout: Number(required(env, "TIMEOUT")),
    };
}

const settings = loadSettings({ PORT: "9090", TIMEOUT: "30" });

console.log(settings.port);
console.log(settings.timeout);
console.log(settings.port + settings.timeout);

Output:

9090
30
9120

A declaration claiming PORT: string would let you read process.env.PORT as a guaranteed string even when it is absent, which is a lie the compiler cannot catch. The required helper is the measurement the datasheet cannot make: it throws on a missing key at start-up rather than letting an undefined masquerade as a string. Here both keys are present, so port is 9090, timeout is 30, and their sum is 9120. The lesson is to validate, then trust, not to trust a declaration that was never checked.

Declaration reference

The common declaration needs and what each calls for are laid out below.

NeedApproach
an untyped npm packagea declare module for that package name
add to an existing package's typesimport the package, then declare module to merge
a global variablea declare global with a const declaration
asset imports such as imagesa declare module for the file glob
environment variablesaugment the process environment interface
a quick escape hatcha bare declare module, typing it all as any

Reading the approach column, the first four describe things the compiler cannot otherwise see, the fifth is the env case that must still be validated, and the last is the escape hatch to avoid except as a stopgap.


Real World Example: A Plugin Command Registry

A tool exposes a registry of commands that plugins extend by merging into a shared Commands interface, so each plugin adds its command's signature to the type and its implementation to the runtime map. A dispatcher then runs a fixed sequence of calls through the registry and reports the results. This is the declaration-merging idea applied exactly as a plugin ecosystem uses it.

// src/registry.ts
// Two "plugins" merge their commands into one interface
interface Commands {
    add: (a: number, b: number) => number;
}
interface Commands {
    mul: (a: number, b: number) => number;
}

const commands: Commands = {
    add: (a, b) => a + b,
    mul: (a, b) => a * b,
};

function pad(text: string, width: number): string {
    const gap = width - text.length;
    return text + " ".repeat(gap > 0 ? gap : 0);
}

const calls: Array<{ name: keyof Commands; a: number; b: number }> = [
    { name: "add", a: 4, b: 5 },
    { name: "mul", a: 6, b: 7 },
    { name: "add", a: 10, b: 20 },
];

let total = 0;
console.log("calls: " + calls.length);
console.log(pad("CMD", 6) + "RESULT");
for (const call of calls) {
    const result = commands[call.name](call.a, call.b);
    total += result;
    console.log(pad(call.name, 6) + result);
}
console.log("total: " + total);

Output:

calls: 3
CMD   RESULT
add   9
mul   42
add   30
total: 81

The two Commands declarations merge into one interface carrying both add and mul, so the commands object literal must implement both or it fails to compile. The three calls run through the registry in order: add(4, 5) gives 9, mul(6, 7) gives 42, and add(10, 20) gives 30, summing to 81. Using keyof Commands for the name field means a call to a command the interface does not declare is rejected at compile time, so the dispatcher only ever indexes a key the type knows.

The value here is the plugin pattern: a plugin file can add its command to the Commands interface through merging and the dispatcher picks it up with no central list to edit, which is why declaration merging underpins so many extensible tools. The interface is the single evolving datasheet, and each plugin contributes an errata sheet to it.

That very openness is the design's real flaw, and it maps straight back to the datasheet analogy. Because any file can merge a member into Commands, the interface's true shape depends on which files the compiler happens to include, and nothing links a declared command to an actual entry in the runtime commands object once the files are separate; a plugin that augments the interface but whose implementation is not loaded leaves a command that is typed as present yet is undefined at runtime, so commands[name](...) throws, which is precisely the datasheet claiming a pin the part does not have. Two smaller limits sit alongside: the report sums the results of add and mul into one total, conflating unrelated operations into a number that means little; and the registry has no way to detect a name collision, so two plugins that both merge an add command silently agree only if their signatures match and otherwise produce a confusing merge error far from either plugin.


Common Mistakes

  1. Forgetting the top-level import in an augmentation file. Without it the .d.ts is a global script and declare module replaces the library's types instead of merging with them.
  2. Putting implementation in a .d.ts. Function bodies and initialised constants are errors in a declaration file; it may contain declarations only, never runtime code.
  3. Using a type alias where merging is needed. A type alias cannot be reopened, so only an interface supports the declaration merging that augmentation relies on.
  4. Leaving a bare declare module "pkg"; in place permanently. It types the entire package as any, which silences errors while discarding every bit of safety.
  5. Keeping a .d.ts outside the compiler's include. If tsconfig never picks the file up, the declarations have no effect and the mystery is why nothing changed.
  6. Declaring an environment variable as a required string. The declaration is a claim the runtime does not honour, so a missing variable becomes undefined wearing a string type.
  7. Installing @types/x for a package that ships its own types. The duplicate declarations collide and produce confusing duplicate-identifier errors.
  8. Trusting a merged interface's shape across files. Because any file can merge in members, the true interface depends on what is compiled, so a typed member can be missing at runtime.
  9. Assuming a declaration verifies anything. A .d.ts describes a shape and never checks it, so anything crossing a runtime boundary still needs a real validation step.

Best Practices

  • Check for bundled types first, then @types, then hand-write. Only author a .d.ts yourself when neither the package nor DefinitelyTyped provides one.
  • Keep declarations in a types folder inside include. Commit them like source and make sure tsconfig actually picks the folder up.
  • Type only the surface you use. A partial but honest declaration beats a complete guess, because the compiler trusts every word of it.
  • Always start an augmentation file with an import of the module. That single line is what makes declare module merge rather than replace.
  • Generate your own library's declarations. Turn on declaration in tsconfig so the .d.ts files come from your source instead of being maintained by hand.
  • Validate environment variables at start-up. Read and check them once, then export a typed config object rather than trusting a process.env augmentation everywhere.
  • Prefer interface for anything meant to be extended. Its openness is the feature that lets consumers and plugins augment your types cleanly.
  • Treat the escape hatch as temporary. A bare declare module unblocks you today, but replace it with a real declaration before it hides a genuine mismatch.

Practice Exercises

  1. The Datasheet. Write a .d.ts for an imaginary tiny-toast package that exports a toast(message: string, options?: { duration?: number }): number function and a named dismissAll(): void, and confirm a consuming import type-checks against it.
  2. The Errata Sheet. Add a requestId: string property to a library's Request interface through module augmentation, then remove the top-level import and observe how the file's meaning changes from augment to replace.
  3. The Honest Environment. Write a loadSettings function that reads three environment variables through a required-key helper, converts their types, and returns a typed object, throwing a clear error on any missing key.
  4. The Registry. Build a command registry where two merged interface declarations contribute add and sub commands, dispatch a fixed list of calls through it, and show what happens at runtime if a declared command has no matching entry in the implementation object.