Sometimes you want to add new features or fix types in libraries you did not write. Augmenting lets you safely add or change types without changing the original code.
Augmenting third-party libraries in Typescript
declare module 'library-name' { // add or change types here interface SomeInterface { newProperty: string; } function newFunction(param: number): void; }
Use declare module 'library-name' to tell TypeScript you are adding types to that library.
Put your new or changed types inside the block. This merges with existing types.
myCustomMethod to lodash's main interface.declare module 'lodash' { interface LoDashStatic { myCustomMethod(): string; } }
user property to Express's Request object to store user info.declare module 'express-serve-static-core' { interface Request { user?: { id: string }; } }
This program adds a new method shout to lodash that makes text uppercase and adds an exclamation mark. Then it calls it and prints the result.
import _ from 'lodash'; declare module 'lodash' { interface LoDashStatic { shout(text: string): string; } } _.shout = function(text: string) { return text.toUpperCase() + '!'; }; console.log(_.shout('hello'));
Augmentations only affect TypeScript's type system, not the actual JavaScript code. You must add the implementation yourself.
Put augmentations in a .d.ts file or at the top of your TypeScript file before usage.
Be careful to match the module name exactly as the library exports it.
Augmenting lets you add or fix types in third-party libraries without changing their code.
Use declare module 'library-name' and add your new types inside.
Remember to add the actual code for new features yourself.