Declaration Merging
February 9, 20261 min readpart 11/20
Difficulty: Intermediate. Prerequisites: Interfaces, namespaces, modules, declaration files.
Declaration merging combines multiple declarations with the same name into a single definition. This enables extending existing types, augmenting third-party libraries, and is foundational for HKT simulation patterns.
Key concepts
- Interface merging: properties combined
- Namespace merging: exports combined
- Module augmentation for extending third-party types
- Global augmentation
- Namespace + class/enum merging
Example
// Interface merging
interface User { name: string; }
interface User { age: number; }
// Merged: { name: string; age: number }
// Module augmentation
declare module 'express' {
interface Request { user?: { id: string; role: string } }
}
// Namespace + class merging
class Album { label: Album.Label; constructor(l: Album.Label) { this.label = l; } }
namespace Album {
export interface Label { name: string }
export function create(l: Label) { return new Album(l); }
}
// Global augmentation
declare global {
interface Array<T> { first(): T | undefined }
}
// Enum + namespace merging
enum Color { Red, Green, Blue }
namespace Color {
export function parse(s: string): Color | undefined {
return Color[s as keyof typeof Color];
}
}
// Real-world: NextAuth — declare module 'next-auth' { interface Session { user: { role: string } } }Resources
- TypeScript Handbook - Declaration Merging: Official documentation
- DefinitelyTyped: Real-world examples
Practice
- Declare Global (TypeHero, Medium)
- Module Augmentation (TypeHero, Medium)
- Modules and Declaration Merging (Total TypeScript, Medium)
- Playground: Interface Merging (TS Playground, Easy)
Hints
- Interfaces with the same name automatically merge their members.
- Use "declare module" to augment types from third-party packages.