Skip to content

Declaration Merging in TypeScript

// First declaration
interface User {
name: string;
}
// Second declaration — merged
interface User {
age: number;
}
// Result:
const user: User = { name: "Alice", age: 30 }; // Both required
express.d.ts
import 'express';
declare module 'express' {
interface Request {
user?: { id: string; role: string };
requestId: string;
}
}
// Now Request has user and requestId globally
app.use((req, res, next) => {
console.log(req.requestId); // OK
next();
});
globals.d.ts
declare global {
interface Window {
__APP_CONFIG__: { apiUrl: string; env: string };
}
namespace NodeJS {
interface ProcessEnv {
MY_SECRET: string;
}
}
}
Use CaseExample
Adding properties to 3rd party typesExpress Request.user
Environment variables typingprocess.env types
Global window propertieswindow.APP_CONFIG
Splitting large interfacesAcross multiple files

Easy: What is declaration merging?

Medium: How do you use module augmentation to extend Express Request?

Hard: What are the risks of declaration merging?