Back to Blog
TypeScriptModule AugmentationTypesAdvanced

TypeScript Module Augmentation

Extend existing types in TypeScript. From declaration merging to global augmentation to library extensions.

B
Bootspring Team
Engineering
June 29, 2021
6 min read

Module augmentation extends existing types without modifying source code. Here's how to use it.

Basic Module Augmentation

Loading code block...

Global Augmentation

Loading code block...

Declaration Merging

Loading code block...

Extending Third-Party Libraries

Loading code block...

Environment Variables

Loading code block...

Extending Built-in Types

Loading code block...

Library Type Definitions

Loading code block...

Path Aliases

Loading code block...

Testing Augmentation

Loading code block...

Best Practices

Organization: ✓ Put declarations in types/ directory ✓ Name files descriptively (express.d.ts) ✓ Include in tsconfig.json ✓ Export {} to make modules Safety: ✓ Don't override existing types carelessly ✓ Use optional properties when uncertain ✓ Document augmentations ✓ Keep augmentations minimal Patterns: ✓ Extend Request/Response for auth ✓ Type environment variables ✓ Augment testing matchers ✓ Add global utilities sparingly

Conclusion

Module augmentation extends existing types without modifying source code. Use it for adding properties to Express requests, typing environment variables, extending third-party libraries, and creating global utilities. Keep augmentations organized and documented for maintainability.

Share this article

Help spread the word about Bootspring

Related articles