TypeScript Declaration Merging
TypeScript Declaration Merging: Extending Library Types Cleanly
Declaration merging happens when TypeScript combines two or more separate declarations sharing the same name into one single definition. While accidental merging can surprise you, intentional module augmentation is how developers add custom fields like req.user to Express or custom claims to NextAuth sessions.
Interfaces merge automatically across the same scope; type aliases never merge and always raise a duplicate identifier error.
Interface Merging vs. Module Augmentation
Declaring the same interface twice combines their properties into one contract:
interface PluginConfig {
name: string;
}
interface PluginConfig {
retries: number;
}
const cfg: PluginConfig = { name: "cache", retries: 3 };
console.log(cfg);
To extend an external npm library inside a .d.ts file (for example, src/types/express.d.ts), wrap the interface inside declare module "...":
// src/types/express.d.ts
import "express-serve-static-core";
declare module "express-serve-static-core" {
interface Request {
requestId?: string;
}
}
Important Rule: Include an import or export
For declare module inside a .d.ts file to augment an existing package rather than overwriting the whole module's types, the file must be a module (contain at least one top-level import or export {}).
Common Mistakes to Avoid
- Writing
declare module "express"without animportin the.d.tsfile: A file with noimport/exporttreatsdeclare moduleas a full replacement and wipes out all of Express's built-in types. - Changing an existing property's type during merging: Adding a new property works cleanly, while redeclaring an existing property with an incompatible type triggers a compiler error.
- Augmenting non-optional fields globally: Mark injected middleware fields optional (
requestId?: string) unless guaranteed on every single request.
Frequently Asked Questions
Can type aliases participate in declaration merging?
No. type aliases cannot be reopened or merged, which is the main reason third-party libraries expose extensibility via interface.
What if two merged interfaces declare the same method name with different parameters?
TypeScript merges them into function overloads, with later declarations taking higher overload priority.
How do I add custom properties to window in browser TypeScript?
Create global.d.ts with export {}; declare global { interface Window { __APP_VERSION__?: string; } }.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.