Web Development
TypeScript
Subjective
Oct 04, 2025
Explain the module augmentation pattern in TypeScript.
Detailed Explanation
Module augmentation extends existing modules by declaring additional properties or methods.
Basic Module Augmentation:
// Extending global interfaces
declare global {
interface Window {
myCustomProperty: string;
myCustomMethod(): void;
}
}
// Now you can use it
window.myCustomProperty = 'Hello';
window.myCustomMethod = () => console.log('Custom method');
Augmenting Third-Party Libraries:
// Extending Express Request interface
import { Request } from 'express';
declare module 'express-serve-static-core' {
interface Request {
user?: {
id: string;
email: string;
};
sessionId?: string;
}
}
// Now you can use req.user with type safety
app.use((req, res, next) => {
req.user = { id: '123', email: 'user@example.com' };
next();
});
Augmenting Node.js Global:
// Adding custom properties to Node.js global
declare global {
namespace NodeJS {
interface Global {
myAppConfig: {
apiUrl: string;
version: string;
};
}
}
}
// Usage
global.myAppConfig = {
apiUrl: 'https://api.example.com',
version: '1.0.0'
};
Augmenting Existing Modules:
// Extending Array prototype
declare global {
interface Array {
first(): T | undefined;
last(): T | undefined;
}
}
Array.prototype.first = function(this: T[]): T | undefined {
return this[0];
};
Array.prototype.last = function(this: T[]): T | undefined {
return this[this.length - 1];
};
// Usage with type safety
const numbers = [1, 2, 3];
const first = numbers.first(); // Type: number | undefined
const last = numbers.last(); // Type: number | undefined
Library-Specific Augmentation:
// Extending jQuery (if using)
declare module 'jquery' {
interface JQuery {
customPlugin(options?: any): JQuery;
}
}
// Extending Lodash
import { LoDashStatic } from 'lodash';
declare module 'lodash' {
interface LoDashStatic {
customUtility(input: T): T;
}
}
Benefits:
• Add type safety to existing libraries
• Extend global objects safely
• Maintain compatibility with third-party code
• Enable custom functionality with type checking.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts