Declaration Merging in TypeScript
Declaration Merging in TypeScript
Section titled “Declaration Merging in TypeScript”Interface Merging
Section titled “Interface Merging”// First declarationinterface User { name: string;}
// Second declaration — mergedinterface User { age: number;}
// Result:const user: User = { name: "Alice", age: 30 }; // Both requiredModule Augmentation
Section titled “Module Augmentation”import 'express';
declare module 'express' { interface Request { user?: { id: string; role: string }; requestId: string; }}
// Now Request has user and requestId globallyapp.use((req, res, next) => { console.log(req.requestId); // OK next();});Global Augmentation
Section titled “Global Augmentation”declare global { interface Window { __APP_CONFIG__: { apiUrl: string; env: string }; } namespace NodeJS { interface ProcessEnv { MY_SECRET: string; } }}When to Use Declaration Merging
Section titled “When to Use Declaration Merging”| Use Case | Example |
|---|---|
| Adding properties to 3rd party types | Express Request.user |
| Environment variables typing | process.env types |
| Global window properties | window.APP_CONFIG |
| Splitting large interfaces | Across multiple files |
Interview Questions
Section titled “Interview Questions”Easy: What is declaration merging?
Medium: How do you use module augmentation to extend Express Request?
Hard: What are the risks of declaration merging?