Writing declaration files and module augmentation

Intermediate · 10 min

Typing an untyped package with declare module, then extending a library's or the global scope's types with module augmentation and declare global.

Before thisDeclaration files and DefinitelyTypedDeclaration merging

LearnAwesome · 10 min

Writing declaration files and module augmentation

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by LearnAwesomeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `declare module "name" { ... }` in a `.d.ts` file describes a package that has no types. List only what you call, and the compiler checks your code against it.
  • `declare module "name";` with no body makes every import from that package `any`, and a wildcard like `declare module "*.svg"` types every import whose path matches.
  • Whether a `.d.ts` file has a top-level `import` or `export` changes what `declare module` means: in a file without one it declares a whole module, in a file with one it adds to the existing module.
  • Module augmentation reopens a library's module and merges extra members into its interfaces, such as adding `user` to a web framework's `Request` type.
  • `declare global { ... }` adds to the global scope from inside a module file, for example new properties on `Window` or a `var` for a global constant.
  • Every declaration is a promise the compiler can't verify. If the runtime code doesn't match it, your program type-checks and then fails.

Two jobs for hand-written declarations

The previous lesson covered where types usually come from: the package itself or an @types package. Two situations fall outside that.

  1. A package has no types anywhere. It’s an internal library, or too small for anyone to have written @types for it.
  2. A package has types, but you’ve added to it at runtime. Your middleware attaches req.user, or a script tag puts analytics on window, and the published types know nothing about it.

The first is solved by writing a declaration. The second is solved by augmentation: adding to someone else’s declaration without editing their files.

Describing an untyped package

Say slugify-lite is plain JavaScript with no types. Read its source or README, then describe what you use in a .d.ts file inside your project:

// src/types/slugify-lite.d.ts
declare module "slugify-lite" {
  export interface SlugifyOptions {
    separator?: string;
    lower?: boolean;
  }

  export function slugify(input: string, options?: SlugifyOptions): string;
  export const version: string;
}

As long as the file is matched by your tsconfig include, imports of "slugify-lite" now get these types, and mistakes are caught:

import { slugify } from "slugify-lite";

slugify("Hello World", { lowercase: true });
// error TS2353: Object literal may only specify known properties,
// and 'lowercase' does not exist in type 'SlugifyOptions'.

You don’t need to describe the whole library on day one. Declare what you call and grow it as you go. Two shortcuts help:

declare module "legacy-lib";   // exists, everything from it is any

declare module "*.svg" {        // any import ending in .svg
  const url: string;
  export default url;
}

The first silences TS7016 and gives up all checking, so treat it as a placeholder. The wildcard form is how bundler setups type imports of images, styles, and other non-code files.

Keep in mind that the compiler can’t check these files against the JavaScript. If slugify really returns null for empty input, your declaration has hidden that, and the bug shows up at runtime.

Script or module: one detail changes everything

A .d.ts file with no top-level import or export is a script. Everything in it is global, and declare module "x" declares a module called x from scratch.

Add a single top-level import or export and it becomes a module. Now declare module "x" means “reopen the existing x and add to it”. Same syntax, opposite effect. That second meaning is module augmentation.

Module augmentation

Suppose a web framework, web-server, ships this type:

export interface Request {
  url: string;
  headers: Record<string, string>;
}

Your auth middleware sets req.user. To tell the compiler, reopen the module from a module file:

// src/types/web-server.d.ts
import "web-server";

declare module "web-server" {
  interface Request {
    user?: { id: string; role: "admin" | "member" };
  }
}

This works because of declaration merging: your Request interface and the library’s merge into one, so every handler now sees req.user. The module name must match the one you import, and you can only merge into things that already merge, mainly interfaces and namespaces. A type alias in the library can’t be extended this way.

Leave out that import "web-server"; line and the file is a script again. Your block then replaces the library’s types, and imports like createServer stop existing. That’s the most common augmentation bug, and the error messages point at your usage, not at the declaration file.

Many libraries expect this pattern and expose an interface specifically for you to extend. Check a library’s docs for “module augmentation” before reaching for type assertions.

declare global

Globals work the same way. From inside a module file, declare global reopens the global scope:

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

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

window.analytics.track("boot") and __APP_VERSION__ now type-check everywhere. The export {}; matters. Without it the file is a script, and TypeScript reports that global augmentations can only be nested in modules. Use var for global values, since only var describes a property of globalThis. This is also how you add environment variables to ProcessEnv from a module file, using the NodeJS namespace shown in namespaces.

What the video covers

LearnAwesome’s walkthrough handles the first half of this lesson hands-on. It takes an untyped CommonJS library, reads its code to work out the types, writes a declare module declaration file, connects it through tsconfig.json, and tests the result. It doesn’t cover augmentation, which is why the later sections above go further. For that, Covalence’s video in the links extends the published types of libraries such as Express, which is the Request example above in a real framework. Pedro Figueiredo’s meetup talk covers patterns for extending external libraries’ types, including global augmentation.

Check yourself

  1. 01You write `declare module "web-server" { interface Request { user?: User } }` in a `.d.ts` file with no imports, and suddenly `createServer` is missing from `web-server`. Why?

    A `.d.ts` file with no top-level `import` or `export` is a global script, and in a script `declare module` declares the entire module. Your three lines replaced the library's real types instead of adding to them. Adding `import "web-server";` at the top makes the file a module, which turns the block into an augmentation.

  2. 02What is the difference between `declare module "legacy-lib";` and writing out a full `declare module "legacy-lib" { ... }` block?

    The one-line version tells the compiler the module exists and makes everything imported from it `any`, so nothing is checked. The full block describes each export, so mistyped option names and wrong argument types are caught at compile time.

  3. 03Why must `declare global` appear in a file that has an `import` or `export`?

    In a file without them, every top-level declaration is already global, so there is nothing to escape from. TypeScript only allows `declare global` inside a module (or inside a `declare module` block) and reports an error otherwise. A bare `export {};` is the usual way to make a declaration file a module.

  4. 04Why is a global constant added through `declare global` written with `var` instead of `const`?

    Only `var` declarations become properties of `globalThis`, which is where values injected by a bundler or script tag actually live. `let` and `const` in a global declaration describe a different kind of binding, so `var` is the accurate description.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark