Declaration MergingAdvanced
1Question 1 of 1
typescriptWhat is Declaration Merging and when is it useful in TypeScript?
Explanation & Concept
Declaration Merging occurs when the TypeScript compiler merges two separate declarations with the exact same name into a single definition.
It is commonly used to extend third-party library types or augment global scopes (e.g. adding custom properties to `window` or Express `Request`).
Code Example
typescript
// Augment the global Express Request object
declare global {
namespace Express {
interface Request {
currentUser?: {
id: string;
email: string;
};
}
}
}
// In an Express handler:
// req.currentUser.id is now fully recognized by TypeScript!How It Works & Key Takeaways
Declaration merging allows safely extending external types without modifying node_modules source files.
Mock Test · 1 Questions · Optional
Ready for Strict Mode & Type Safety?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions