0
0
Typescriptprogramming~7 mins

Augmenting third-party libraries in Typescript

Choose your learning style9 modes available
Introduction

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.

You want to add a new function or property to a library's type definitions.
You need to fix or improve incorrect or missing types in a third-party library.
You want to extend interfaces or modules from a library to fit your app's needs.
You want to add custom types for library features that are not typed yet.
Syntax
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.

Examples
This adds a new method myCustomMethod to lodash's main interface.
Typescript
declare module 'lodash' {
  interface LoDashStatic {
    myCustomMethod(): string;
  }
}
This adds a user property to Express's Request object to store user info.
Typescript
declare module 'express-serve-static-core' {
  interface Request {
    user?: { id: string };
  }
}
Sample Program

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.

Typescript
import _ from 'lodash';

declare module 'lodash' {
  interface LoDashStatic {
    shout(text: string): string;
  }
}

_.shout = function(text: string) {
  return text.toUpperCase() + '!';
};

console.log(_.shout('hello'));
OutputSuccess
Important Notes

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.

Summary

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.