Sub topic 12
Extending Existing Modules with Augmentation
This chapter assumes you can read basic TypeScript types and interfaces, know how import and export work, and have seen declare module in an ambient declaration. Earlier chapters covered how a file becomes a module and how ambient declarations describe untyped packages. Here you will reopen types that already exist and add to them.
What augmentation is
Module augmentation adds declarations to a module that is defined somewhere else. You do not edit the original file or the package in node_modules. You write a second declaration that the compiler merges into the first.
The mechanism behind it is declaration merging. When TypeScript sees two declarations with the same name in the same scope, it combines some kinds of them into one definition. Interfaces merge. Namespaces merge. A namespace can merge with a class, function, or enum. Type aliases and classes do not merge with themselves, so you cannot add members to a class or alias this way.
Typical uses:
- Adding a property to a request object that middleware fills in.
- Adding a method to an interface from a third-party library.
- Declaring extra keys on a library's configuration or theme type.
- Adding a global variable or a method on a built-in type such as
Array.
The core rule: the file must be a module
The same declare module "x" text means two different things depending on the file it sits in.
- In a script (a file with no top-level
importorexport),declare module "x" { ... }is an ambient module declaration. It defines or replaces the module"x". - In a module (a file with at least one top-level
importorexport),declare module "x" { ... }is an augmentation. It merges into the existing module"x".
This is why the example below starts with an import.
// user.ts
export interface User {
id: number;
}
// user-extras.ts
import "./user.js";
declare module "./user.js" {
interface User {
nickname?: string;
}
}The line import "./user.js"; is a side-effect import. It adds no names to the file, but it makes user-extras.ts a module, so the declaration is an augmentation. It also forces the compiler to load user.ts, which guarantees there is something to merge with.
If you delete the import, the file becomes a script. TypeScript then treats declare module "./user.js" as an ambient declaration. Relative module names are not allowed in ambient declarations, so you get an error, and for a package name you would silently replace the package's types instead of extending them.
After the augmentation is part of the program, every file sees the new property:
// app.ts
import type { User } from "./user.js";
const u: User = { id: 1, nickname: "ada" };
console.log(u.nickname?.toUpperCase());app.ts does not import user-extras.ts. It does not need to. Augmentations apply program-wide, as long as the augmenting file is included in the compilation.
How the module specifier is matched
The string in declare module "..." must resolve to the same file as the import you want to extend. TypeScript resolves it with the same rules it uses for imports, so relative paths are relative to the augmenting file.
In the example, "./user.js" resolves to user.ts under nodenext, the same way an import would. If you wrote "./user" and your resolution mode requires extensions, the specifier would not resolve and the augmentation would fail. Use the same specifier style you use for imports.
For a package, use the package name:
// express-augment.ts
import "express";
declare module "express-serve-static-core" {
interface Request {
userId?: string;
}
}Note the target. The Request interface that Express users see is re-exported from express-serve-static-core. You must augment the module where the interface is declared, not a module that only re-exports it. If the augmentation seems to have no effect, check where the library's type declaration actually lives, by using go-to-definition in your editor.
What you can and cannot add
Augmentation has limits worth memorizing.
| You want to | Works? | Notes |
|---|---|---|
| Add members to an interface | Yes | Declared with `interface Name { ... }` inside the block |
| Add overloads to a function | Yes | Via a merged namespace or a repeated function declaration, depending on how the original is declared |
| Add a new top-level export | Limited | You can declare new names, but no runtime value appears |
| Add members to a class | Partly | Declare an interface with the same name to add instance members. The runtime must supply them |
| Add a new default export | No | Augmentations cannot add default exports |
| Replace an existing property's type | No | A later property declaration with a different type is a "subsequent property declarations must have the same type" error |
| Rewrite a type alias | No | Aliases do not merge |
Two points deserve emphasis.
First, augmentation changes only types. It generates no JavaScript. If you declare nickname on User, nothing creates it. Your code must set it, or your types lie.
Second, you cannot change an existing member's type, only add new members. If you need a narrower or different type, you usually need a different design, such as a wrapper type, an intersection, or a generic parameter that the library already exposes for this purpose.
Merging a class with an interface
A common pattern is adding methods to a class you do not own, for example by assigning to its prototype.
// shout.ts
import { Greeter } from "./greeter.js";
declare module "./greeter.js" {
interface Greeter {
shout(): string;
}
}
Greeter.prototype.shout = function (this: Greeter): string {
return this.greet().toUpperCase() + "!";
};The augmentation tells the compiler that shout exists. The assignment makes it exist at runtime. Both are your responsibility. If another file uses shout but never imports shout.ts, the type check passes and the call fails at runtime because the assignment never ran. Import the file for its side effect wherever the method is needed, or import it once at your program's entry point.
Global augmentation
Some values are not in any module: window, process, Array. To extend these, use declare global inside a module file.
// globals.ts
export {};
declare global {
interface Window {
appVersion: string;
}
interface Array<T> {
last(): T | undefined;
}
}
Array.prototype.last = function <T>(this: T[]): T | undefined {
return this[this.length - 1];
};
window.appVersion = "1.4.0";export {}; makes the file a module. declare global is only allowed in module files, or in ambient module declarations. In a script file, you would skip declare global and write the interface at the top level, since script declarations are already global.
Extending built-in prototypes is legal but has costs. Every file in the program sees the change, other libraries may add conflicting members, and the runtime patch must run before the first call. Prefer a plain function such as last(items) unless you have a strong reason.
Making sure the augmentation is loaded
An augmentation takes effect only when the compiler includes its file. Three things control that:
- The
include,files, andexcludeoptions intsconfig.json. - Imports reachable from the files that are included.
typesandtypeRoots, which restrict which@typespackages load automatically.
A frequent failure: you put the augmentation in src/types/express.d.ts, but include lists only src/index.ts's directory with a different pattern, or the file is excluded. The code compiles in your editor, which may have loaded the file anyway, and fails on the command line, or the reverse. When behavior differs between the editor and tsc, run tsc --listFiles and look for your augmentation.
A .d.ts file that augments must still contain a top-level import or export. Declaration files follow the same script and module rule.
Common errors
- "Invalid module name in augmentation. Module 'x' resolves to an untyped module." The module has no types, so there is nothing to merge with. Write an ambient declaration instead, or install types.
- "Cannot find module './user.js'" in the augmentation. The specifier does not resolve from the augmenting file. Match your import style and check the path.
- "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." Add
export {}or an import to the file. - The property is not found even though the augmentation exists. The file is not in the program, or you augmented a re-exporting module instead of the declaring one.
- "Subsequent property declarations must have the same type." You tried to redeclare an existing property with a different type. Add a new property or change your design.
- The type checks but the value is
undefinedat runtime. Augmentation adds no code. Something must assign the value.
Choosing augmentation or something else
Use augmentation when the library is designed around shared mutable state, such as a request object, and the library's documentation endorses extending it. Avoid it when you can pass a typed value explicitly, wrap the library type in your own interface, or use a generic parameter the library provides. Augmentation is global, which makes it convenient and also makes it hard to scope to one part of a program or to remove later.
Exercise
A file session.d.ts contains only declare module "express-serve-static-core" { interface Request { sessionId?: string } }, with no import or export. Your code still reports that sessionId does not exist on Request, and Express's other Request members are now missing too. What is wrong, and how do you fix it?
Show answer
With no top-level import or export, the file is a script, so the declare module is an ambient module declaration that replaces the real module's types instead of merging with them. Add import "express"; (or export {};) at the top so the file is a module and the block becomes an augmentation. Make sure the file is included in the compilation.
Exercise
You add interface Window { appVersion: string } inside declare global in a module file, but at runtime window.appVersion is undefined. Why does the compiler not catch this, and what must you do?
Show answer
Augmentation only changes types and emits no JavaScript. You must assign window.appVersion = "..." in code that runs before the value is read, for example at the program's entry point.