Augmenting Third-Party Interfaces
What you'll learn: How to safely add custom properties or methods to library interfaces in your own code using declaration merging.
The Power of Declaration Merging with Libraries
Sometimes a third-party library's TypeScript definitions are incomplete, outdated, or don't reflect customizations you've made. Instead of forking the library's type definitions or using any, you can augment the library's interfaces directly in your own codebase using declaration merging.
This is the same merging behavior we've seen before, but applied strategically to extend types you don't control.
How It Works
You create a declaration file (.d.ts) or add declarations in your code that match the exact module and interface names from the library. TypeScript merges your additions with the original definitions.
Example: Adding a custom property to an Express request:
// In your code: express-extensions.d.ts
declare module 'express' {
interface Request {
userId?: string; // Your custom property
}
}
Now throughout your app, Request.userId is recognized by TypeScript, even though it doesn't exist in the original Express types.
Safety Rules
- Match the module and interface names exactly — typos create new types instead of merging
- Only add properties, never change existing ones — you can't override what's already there
- Document your extensions — future developers need to know these aren't standard library features
- Keep extensions in dedicated files — makes them easy to find and maintain
Key Takeaway: Declaration merging lets you extend third-party library interfaces safely in your own code without modifying the library itself, giving you type-safe access to custom properties or methods you've added at runtime.