How would you use declaration merging to properly type a module augmentation that adds a method to a third-party library's exported class?
Short answer
Combine 'declare module' (to reopen the library's module) with an interface declaration matching the class's name inside it — TypeScript merges your added interface members onto the library's own class type, so instances gain the new property/method in the type system (though…
Advertisement
AModel answer
Combine 'declare module' (to reopen the library's module) with an interface declaration matching the class's name inside it — TypeScript merges your added interface members onto the library's own class type, so instances gain the new property/method in the type system (though you're still responsible for ACTUALLY implementing that behavior at runtime, e.g. via monkey-patching or a plugin system).
// dayjs-plugin.d.ts
import 'dayjs';
declare module 'dayjs' {
interface Dayjs {
fromNow(): string; // added by a plugin like dayjs/plugin/relativeTime
}
}
// usage.ts
import dayjs from 'dayjs';
dayjs().fromNow(); // now type-checks correctlyReal-world example
Writing plugin type augmentations for a library like Day.js, Vue, or Express whose plugins add real runtime methods to existing classes.
Likely follow-ups
- Why does the augmenting file need to import the original module before declaring the augmentation?
Related topics