JavaScript and TypeScript course ยท Module 10: TypeScript in Practice
Module Augmentation and Declaration Merging
In this lesson3
Imagine that the park bought a ready-made camera system, and you want to add a dinosaurId field to its reports. You cannot edit the vendor's code, because your change would disappear with the next update. Module augmentation and declaration merging are advanced TypeScript features that let you extend existing modules and merge declarations without touching the original. These mechanisms are key when working with external libraries, building plugins and extending frameworks.
Declaration Merging
Declaration merging means that the compiler combines several declarations with the same name into a single definition. It applies to interfaces, namespaces and the pairs class with namespace, function with namespace and enum with namespace. Type aliases (type) and two classes with the same name, on the other hand, do not merge.
Declaration Merging Basics
The most common case is two interfaces with the same name. Alongside it you can see namespaces merging, and a class merged with a namespace that adds types and static functions to it:
// Interface merging - the most common case
interface User {
id: number;
name: string;
}
interface User {
email: string; // Adding a new property
age?: number; // And another optional one
}
// TypeScript automatically merges both declarations
const user: User = {
id: 1,
name: "John Smith",
email: "john@example.com"
// age is optional
};
// Namespace merging
namespace MyApp {
export interface Config {
apiUrl: string;
}
export function initialize(config: Config): void {
console.log("Initializing with:", config.apiUrl);
}
}
namespace MyApp {
export interface Config {
timeout?: number; // Extending the Config interface
}
export class Logger {
log(message: string): void {
console.log(`[MyApp]: ${message}`);
}
}
}
// Using merged declarations
const config: MyApp.Config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
const logger = new MyApp.Logger();
logger.log("Application started");
// Class and namespace merging
class Album {
constructor(public title: string, public artist: string) {}
}
namespace Album {
export interface Track {
number: number;
title: string;
duration: number;
}
export function createFromJSON(json: string): Album {
const data = JSON.parse(json);
return new Album(data.title, data.artist);
}
}
// Using class and namespace together
const album = new Album("The Wall", "Pink Floyd");
const track: Album.Track = {
number: 1,
title: "In The Flesh?",
duration: 196
};
const albumFromJSON = Album.createFromJSON('{"title": "Dark Side", "artist": "Pink Floyd"}');The user object must have the fields from both declarations, and Album works both as a class (new Album(...)) and as a namespace (Album.Track). If both interfaces declare the same field, its types must be identical, otherwise the compiler reports an error.
Function and Namespace Merging
A function merged with a namespace is an object you can call that also has extra fields, as in many JavaScript libraries. The same works with an enum:
// Function and namespace merging - useful for creating callable objects
function createCounter(initial: number = 0): () => number {
let count = initial;
return () => ++count;
}
namespace createCounter {
export interface Options {
initial?: number;
step?: number;
max?: number;
}
export function withOptions(options: Options): () => number {
let count = options.initial || 0;
const step = options.step || 1;
const max = options.max || Infinity;
return () => {
if (count + step > max) {
return count;
}
count += step;
return count;
};
}
export function reset(counter: () => number): void {
// Reset implementation
console.log("Counter reset");
}
}
// Using the function and its namespace
const counter1 = createCounter(10);
const counter2 = createCounter.withOptions({ initial: 0, step: 5, max: 100 });
console.log(counter1()); // 11
console.log(counter2()); // 5
createCounter.reset(counter1);
// Enum and namespace merging
enum Status {
Idle = "IDLE",
Loading = "LOADING",
Success = "SUCCESS",
Error = "ERROR"
}
namespace Status {
export function isComplete(status: Status): boolean {
return status === Status.Success || status === Status.Error;
}
export function isInProgress(status: Status): boolean {
return status === Status.Loading;
}
export interface Metadata {
timestamp: Date;
message?: string;
}
}
// Using enum with additional functions
const currentStatus = Status.Loading;
console.log(Status.isInProgress(currentStatus)); // true
console.log(Status.isComplete(currentStatus)); // falsecreateCounter(10) returns a counter starting at 10, and createCounter.withOptions is a function attached to the same name. The Status enum gained helper methods, while its values stayed the same.
Merging with Generics
Merged generic interfaces must have identical type parameters, including their names. A class then implements the sum of all declarations:
// Generic interface merging
interface Collection<T> {
items: T[];
add(item: T): void;
}
interface Collection<T> {
remove(item: T): boolean;
find(predicate: (item: T) => boolean): T | undefined;
}
class ArrayCollection<T> implements Collection<T> {
items: T[] = [];
add(item: T): void {
this.items.push(item);
}
remove(item: T): boolean {
const index = this.items.indexOf(item);
if (index > -1) {
this.items.splice(index, 1);
return true;
}
return false;
}
find(predicate: (item: T) => boolean): T | undefined {
return this.items.find(predicate);
}
}
// Generic namespace merging
namespace DataStructures {
export interface Node<T> {
value: T;
next?: Node<T>;
}
export class LinkedList<T> {
head?: Node<T>;
add(value: T): void {
const node: Node<T> = { value };
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
}
}
}
namespace DataStructures {
export interface Node<T> {
prev?: Node<T>; // Adding pointer to previous element
}
export class DoublyLinkedList<T> extends LinkedList<T> {
// Doubly linked list implementation
}
}ArrayCollection must have add, remove and find, because Collection<T> is now a single interface. The second part of the DataStructures namespace adds a prev pointer to the node.
Module Augmentation
Module augmentation means extending the types of someone else's module. You import the original module (which makes the file a module), open its declaration with declare module 'name', add new fields or methods to the interface, and TypeScript merges the declarations by itself. For a local file you would write, for example, declare module './dinosaur' { interface Dinosaur { fly(): void } }.
Extending External Modules
We add user data to the Express request and helper methods to the response. We extend express-serve-static-core, because that is where the types of req and res in handlers come from:
// Extending Express types (req and res in handlers come from express-serve-static-core)
declare module "express-serve-static-core" {
interface Request {
user?: {
id: string;
email: string;
roles: string[];
};
requestId?: string;
}
interface Response {
sendSuccess(data: any): void;
sendError(error: Error, statusCode?: number): void;
}
}
// Extension implementation
import express from "express";
const app = express();
// Middleware adding user and requestId
app.use((req, res, next) => {
req.requestId = crypto.randomUUID();
// Authentication and adding user
req.user = {
id: "123",
email: "user@example.com",
roles: ["user", "admin"]
};
next();
});
// Extending Response with new methods
app.use((req, res, next) => {
res.sendSuccess = function(data: any) {
this.json({
success: true,
data,
requestId: req.requestId
});
};
res.sendError = function(error: Error, statusCode: number = 500) {
this.status(statusCode).json({
success: false,
error: error.message,
requestId: req.requestId
});
};
next();
});
// Using extended types
app.get("/profile", (req, res) => {
if (!req.user) {
return res.sendError(new Error("Unauthorized"), 401);
}
res.sendSuccess({
user: req.user,
requestId: req.requestId
});
});The augmentation changes only the types, so a middleware still has to add the implementation of sendSuccess and sendError before a handler uses them. The general rule: extend the module that actually declares the type, not the one that merely re-exports it.
Extending Global Types
A declare global block extends global types such as Window, Array or String. It only works in a file that is a module, so if the file has no imports, add export {} at the end:
// Extending global objects
declare global {
interface Window {
myApp: {
version: string;
config: {
apiUrl: string;
debugMode: boolean;
};
utils: {
formatDate(date: Date): string;
parseJSON<T>(json: string): T | null;
};
};
}
interface Array<T> {
groupBy<K extends keyof T>(key: K): Record<string, T[]>;
chunk(size: number): T[][];
}
interface String {
capitalize(): string;
toSlug(): string;
}
}
// Implementing Array extensions
Array.prototype.groupBy = function<T, K extends keyof T>(this: T[], key: K): Record<string, T[]> {
return this.reduce((acc, item) => {
const groupKey = String(item[key]);
if (!acc[groupKey]) {
acc[groupKey] = [];
}
acc[groupKey].push(item);
return acc;
}, {} as Record<string, T[]>);
};
Array.prototype.chunk = function<T>(this: T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < this.length; i += size) {
chunks.push(this.slice(i, i + size));
}
return chunks;
};
// Implementing String extensions
String.prototype.capitalize = function(this: string): string {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
};
String.prototype.toSlug = function(this: string): string {
return this
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '');
};
// Using extensions
const users = [
{ name: "Jan", age: 30, department: "IT" },
{ name: "Anna", age: 25, department: "HR" },
{ name: "Piotr", age: 35, department: "IT" }
];
const grouped = users.groupBy("department");
console.log(grouped); // { IT: [...], HR: [...] }
const chunks = [1, 2, 3, 4, 5, 6, 7, 8].chunk(3);
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8]]
const title = "hello world from typescript".capitalize();
console.log(title); // "Hello world from typescript"
const slug = "Hello World! From TypeScript".toSlug();
console.log(slug); // "hello-world-from-typescript"
// Window extensions
window.myApp = {
version: "1.0.0",
config: {
apiUrl: "https://api.example.com",
debugMode: true
},
utils: {
formatDate(date: Date): string {
return date.toLocaleDateString("en-US");
},
parseJSON<T>(json: string): T | null {
try {
return JSON.parse(json) as T;
} catch {
return null;
}
}
}
};Technically this works, but I do not recommend extending built-in prototypes. Patches exactly like this one (the Sugar library added its own groupBy to arrays) meant that the standard could not use the name Array.prototype.groupBy, and ES2024 introduced the static Object.groupBy instead. It is safer to write plain helper functions or to extend your own objects, like window.myApp.
Plugin System with Module Augmentation
A plugin system lets different parts of the application add their own context and hook types to a shared module:
// Base plugin system
interface PluginSystem {
plugins: Map<string, Plugin>;
register(plugin: Plugin): void;
execute(hookName: string, context: any): void;
}
interface Plugin {
name: string;
version: string;
hooks?: {
[hookName: string]: (context: any) => void | Promise<void>;
};
}
class PluginManager implements PluginSystem {
plugins = new Map<string, Plugin>();
register(plugin: Plugin): void {
this.plugins.set(plugin.name, plugin);
console.log(`Plugin ${plugin.name} v${plugin.version} registered`);
}
async execute(hookName: string, context: any): Promise<void> {
for (const [name, plugin] of this.plugins) {
if (plugin.hooks && plugin.hooks[hookName]) {
await plugin.hooks[hookName](context);
}
}
}
}
// Extending the plugin system through different modules
declare module "./plugin-system" {
interface PluginContext {
user?: {
id: string;
name: string;
};
request?: {
url: string;
method: string;
};
}
interface PluginHooks {
beforeRequest?: (context: PluginContext) => void;
afterRequest?: (context: PluginContext & { response: any }) => void;
onError?: (context: PluginContext & { error: Error }) => void;
}
}
// Authentication plugin
const authPlugin: Plugin = {
name: "auth",
version: "1.0.0",
hooks: {
beforeRequest(context) {
console.log("Checking authentication...");
if (!context.user) {
throw new Error("Not authenticated");
}
}
}
};
// Logging plugin
const loggingPlugin: Plugin = {
name: "logging",
version: "1.0.0",
hooks: {
beforeRequest(context) {
console.log(`[${new Date().toISOString()}] ${context.request?.method} ${context.request?.url}`);
},
afterRequest(context) {
console.log(`Response for ${context.request?.url}:`, context.response);
},
onError(context) {
console.error(`Error for ${context.request?.url}:`, context.error);
}
}
};
// Using the plugin system
const pluginManager = new PluginManager();
pluginManager.register(authPlugin);
pluginManager.register(loggingPlugin);
// Request simulation
const context = {
user: { id: "123", name: "Jan" },
request: { url: "/api/data", method: "GET" }
};
pluginManager.execute("beforeRequest", context);The declare module './plugin-system' augmentation works only if such a file exists, and the code itself must live in a module. In a file without imports, the Plugin interface would merge with the global Plugin interface from the DOM definitions, which describes browser plugins, and that is declaration merging in its least welcome form.
Practical Applications
Extending UI Libraries
Material UI explicitly encourages augmentation: you add your own theme fields and typography variants to the Theme, ThemeOptions and TypographyVariants interfaces:
// Extending Material-UI
declare module "@mui/material/styles" {
interface Theme {
custom: {
borderRadius: {
small: number;
medium: number;
large: number;
};
animations: {
fast: string;
normal: string;
slow: string;
};
};
}
interface ThemeOptions {
custom?: {
borderRadius?: {
small?: number;
medium?: number;
large?: number;
};
animations?: {
fast?: string;
normal?: string;
slow?: string;
};
};
}
interface TypographyVariants {
label: React.CSSProperties;
caption2: React.CSSProperties;
}
interface TypographyVariantsOptions {
label?: React.CSSProperties;
caption2?: React.CSSProperties;
}
}
declare module "@mui/material/Typography" {
interface TypographyPropsVariantOverrides {
label: true;
caption2: true;
}
}
// Creating an extended theme
import { createTheme } from "@mui/material/styles";
const theme = createTheme({
custom: {
borderRadius: {
small: 4,
medium: 8,
large: 16
},
animations: {
fast: "150ms",
normal: "300ms",
slow: "500ms"
}
},
typography: {
label: {
fontSize: "0.75rem",
fontWeight: 600,
textTransform: "uppercase"
},
caption2: {
fontSize: "0.625rem",
fontWeight: 400
}
}
});
// Using extended types
import { Typography, Box } from "@mui/material";
function CustomComponent() {
return (
<Box
sx={{
borderRadius: (theme) => theme.custom.borderRadius.medium,
transition: (theme) => `all ${theme.custom.animations.normal} ease`
}}
>
<Typography variant="label">Custom Label</Typography>
<Typography variant="caption2">Tiny caption text</Typography>
</Box>
);
}Theme describes the finished theme, while ThemeOptions describes the data passed to createTheme, which is why the fields are optional there. The code contains JSX, so in a project you keep it in a .tsx file.
Extending Frameworks
In the same way you extend the Next.js types for API routes in the Pages Router, adding a session and helper methods:
// Extending Next.js
declare module "next" {
export interface NextApiRequest {
session?: {
user: {
id: string;
email: string;
permissions: string[];
};
expiresAt: Date;
};
// Helper methods
validateBody<T>(schema: any): T;
requireAuth(): void;
hasPermission(permission: string): boolean;
}
export interface NextApiResponse {
success<T>(data: T, statusCode?: number): void;
error(message: string, statusCode?: number): void;
paginated<T>(items: T[], total: number, page: number, pageSize: number): void;
}
}
// Middleware extending Next.js
import { NextApiRequest, NextApiResponse } from "next";
export function withExtensions(
handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>
) {
return async (req: NextApiRequest, res: NextApiResponse) => {
// Add methods to request
req.validateBody = function<T>(schema: any): T {
// Validation implementation
return req.body as T;
};
req.requireAuth = function() {
if (!this.session) {
throw new Error("Authentication required");
}
};
req.hasPermission = function(permission: string): boolean {
return this.session?.user.permissions.includes(permission) || false;
};
// Add methods to response
res.success = function<T>(data: T, statusCode = 200) {
this.status(statusCode).json({
success: true,
data
});
};
res.error = function(message: string, statusCode = 500) {
this.status(statusCode).json({
success: false,
error: message
});
};
res.paginated = function<T>(items: T[], total: number, page: number, pageSize: number) {
this.json({
success: true,
data: items,
pagination: {
total,
page,
pageSize,
totalPages: Math.ceil(total / pageSize)
}
});
};
// Call handler
try {
await handler(req, res);
} catch (error) {
res.error(error instanceof Error ? error.message : "Internal server error");
}
};
}
// Usage in API route
export default withExtensions(async (req, res) => {
req.requireAuth();
if (!req.hasPermission("read:users")) {
return res.error("Insufficient permissions", 403);
}
const data = req.validateBody<{ search?: string }>(/* schema */);
// Business logic
const users = []; // Fetch users
const total = 100;
res.paginated(users, total, 1, 20);
});In the App Router, API routes are handled by Route Handlers based on the standard Request and Response objects, so there you usually write helper functions instead of augmentations. With re-exported types, check which file they come from, just as with Express.
Module augmentation and declaration merging are powerful tools for flexibly extending existing code. The key is understanding when to use each technique and how they can work together in extensible systems. My advice: keep your augmentations in a separate directory, for example types/, so the whole team knows where to look for additions to other people's types. In the editor below you will practice merging declarations, and in the next lesson you will learn Test-Driven Development.
Remember: an augmentation is a sticky note on someone else's park map that erases nothing and only adds new information.
Code for this lesson: index.ts
// Examples of module augmentation and declaration merging
// 1. Interface merging - combining declarations
interface User {
id: number;
name: string;
}
interface User {
email: string; // We add new properties
age?: number; // Optional property
}
// TypeScript automatically merges both declarations
const user: User = {
id: 1,
name: "Jan Kowalski",
email: "jan@example.com",
age: 30
};
// 2. Namespace merging
namespace AppConfig {
export interface Settings {
apiUrl: string;
timeout: number;
}
export function getDefaultSettings(): Settings {
return {
apiUrl: "https://api.example.com",
timeout: 5000
};
}
}
namespace AppConfig {
export interface Settings {
debugMode?: boolean; // We extend the interface
}
export class ConfigManager {
private settings: Settings;
constructor() {
this.settings = getDefaultSettings();
}
updateSettings(updates: Partial<Settings>): void {
this.settings = { ...this.settings, ...updates };
}
getSettings(): Settings {
return this.settings;
}
}
}
// We use the merged declarations
const configManager = new AppConfig.ConfigManager();
configManager.updateSettings({ debugMode: true });
console.log("Settings:", configManager.getSettings());
// 3. Function and namespace merging
function createLogger(prefix: string) {
return {
log(message: string) {
console.log(`[${prefix}] ${message}`);
}
};
}
namespace createLogger {
export interface Options {
timestamp?: boolean;
color?: string;
}
export function withOptions(prefix: string, options: Options) {
return {
log(message: string) {
const timestamp = options.timestamp ? new Date().toISOString() : '';
console.log(`${timestamp} [${prefix}] ${message}`);
}
};
}
export const DEFAULT_OPTIONS: Options = {
timestamp: true,
color: 'default'
};
}
// We use the function and namespace
const logger1 = createLogger("APP");
const logger2 = createLogger.withOptions("DEBUG", { timestamp: true });
logger1.log("Simple message");
logger2.log("Message with a timestamp");
// 4. Extending global types
declare global {
interface Array<T> {
first(): T | undefined;
last(): T | undefined;
groupBy<K extends keyof T>(key: K): Record<string, T[]>;
}
interface String {
capitalize(): string;
toKebabCase(): string;
}
}
// Implementation of the extensions
Array.prototype.first = function<T>(this: T[]): T | undefined {
return this[0];
};
Array.prototype.last = function<T>(this: T[]): T | undefined {
return this[this.length - 1];
};
Array.prototype.groupBy = function<T, K extends keyof T>(
this: T[],
key: K
): Record<string, T[]> {
return this.reduce((groups, item) => {
const groupKey = String(item[key]);
groups[groupKey] = groups[groupKey] || [];
groups[groupKey].push(item);
return groups;
}, {} as Record<string, T[]>);
};
String.prototype.capitalize = function(this: string): string {
return this.charAt(0).toUpperCase() + this.slice(1);
};
String.prototype.toKebabCase = function(this: string): string {
return this
.replace(/([A-Z])/g, '-$1')
.toLowerCase()
.replace(/^-/, '');
};
// Testing the extensions
const numbers = [1, 2, 3, 4, 5];
console.log("First element:", numbers.first()); // 1
console.log("Last element:", numbers.last()); // 5
const products = [
{ name: "Laptop", category: "Electronics", price: 1000 },
{ name: "Mouse", category: "Electronics", price: 50 },
{ name: "Desk", category: "Furniture", price: 300 }
];
const grouped = products.groupBy("category");
console.log("Grouped products:", grouped);
const text = "hello world";
console.log("Capitalize:", text.capitalize()); // "Hello world"
const camelCase = "myVariableName";
console.log("Kebab case:", camelCase.toKebabCase()); // "my-variable-name"
// 5. Class and namespace merging
class EventEmitter {
private events: Map<string, Function[]> = new Map();
on(event: string, handler: Function): void {
if (!this.events.has(event)) {
this.events.set(event, []);
}
this.events.get(event)!.push(handler);
}
emit(event: string, ...args: any[]): void {
const handlers = this.events.get(event);
if (handlers) {
handlers.forEach(handler => handler(...args));
}
}
}
namespace EventEmitter {
export interface EventMap {
connect: { userId: string; timestamp: Date };
disconnect: { userId: string; reason: string };
message: { userId: string; text: string };
}
export type EventHandler<K extends keyof EventMap> =
(data: EventMap[K]) => void;
export function createTypedEmitter() {
const emitter = new EventEmitter();
return {
on<K extends keyof EventMap>(event: K, handler: EventHandler<K>): void {
emitter.on(event, handler);
},
emit<K extends keyof EventMap>(event: K, data: EventMap[K]): void {
emitter.emit(event, data);
}
};
}
}
// We use the typed event emitter
const typedEmitter = EventEmitter.createTypedEmitter();
typedEmitter.on('connect', (data) => {
console.log(`User ${data.userId} connected at ${data.timestamp}`);
});
typedEmitter.on('message', (data) => {
console.log(`${data.userId}: ${data.text}`);
});
typedEmitter.emit('connect', {
userId: 'user123',
timestamp: new Date()
});
typedEmitter.emit('message', {
userId: 'user123',
text: 'Welcome everyone!'
});
// 6. Module augmentation (simulation)
// In a real application this would be in a separate file
interface MyLibrary {
version: string;
utils: {
formatDate(date: Date): string;
};
}
// We extend the library
interface MyLibrary {
plugins: Plugin[];
registerPlugin(plugin: Plugin): void;
}
interface Plugin {
name: string;
init(): void;
}
// Implementation of the extended library
const myLibrary: MyLibrary = {
version: "1.0.0",
utils: {
formatDate(date: Date): string {
return date.toLocaleDateString('en-US');
}
},
plugins: [],
registerPlugin(plugin: Plugin): void {
this.plugins.push(plugin);
plugin.init();
console.log(`Plugin ${plugin.name} registered`);
}
};
// Test
const datePlugin: Plugin = {
name: "DateFormatter",
init() {
console.log("DateFormatter plugin initialized");
}
};
myLibrary.registerPlugin(datePlugin);
console.log("Library version:", myLibrary.version);
console.log("Formatted date:", myLibrary.utils.formatDate(new Date()));
// Export to avoid global declaration errors
export {};Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which declarations can be automatically merged in TypeScript?
Hands-on tasks in the game
- Click in order
Arrange the steps for creating ambient modules.
- Code editor
Extend existing types through declaration merging.
- Click in order
Arrange the elements of a module augmentation declaration:
- Vertical ordering
Arrange the steps of extending a module through module augmentation: