Skip to main content

Merging & Augmenting in TypeScript

In this tutorial, we will explore merging and augmenting in TypeScript. Understanding how to extend existing code and avoid naming collisions will help you manage your code, enabling better organization, collaboration, and maintainability.

Merging Interfaces

TypeScript allows you to merge multiple interface declarations with the same name. The resulting interface will contain all the properties and methods from the combined interfaces:

TypeScript
interface Box {
width: number;
height: number;
}

interface Box {
depth: number;
}

const cube: Box = {
width: 10,
height: 10,
depth: 10,
};

In this example, we merge two Box interfaces. The resulting Box interface contains properties width, height, and depth.

Merging Namespaces

Similar to interfaces, TypeScript allows you to merge multiple namespace declarations with the same name. The resulting namespace will contain all the members from the combined namespaces:

TypeScript
namespace Animals {
export class Dog {
constructor(public name: string) {}

bark() {
console.log(`${this.name} says woof!`);
}
}
}

namespace Animals {
export class Cat {
constructor(public name: string) {}

meow() {
console.log(`${this.name} says meow!`);
}
}
}

const dog = new Animals.Dog('Buddy');
dog.bark(); // Output: Buddy says woof!

const cat = new Animals.Cat('Whiskers');
cat.meow(); // Output: Whiskers says meow!

In this example, we merge two Animals namespaces. The resulting Animals namespace contains classes Dog and Cat.

Augmenting Modules

You can also extend existing modules by adding new properties or methods to them. To do this, you need to declare a module with the same name and export the new members:

TypeScript
// math.ts
export function add(a: number, b: number): number {
return a + b;
}

// math-extended.ts
import * as math from './math';

declare module './math' {
export function subtract(a: number, b: number): number;
}

math.subtract = (a: number, b: number) => a - b;

// main.ts
import * as math from './math-extended';

console.log(math.add(1, 2)); // Output: 3
console.log(math.subtract(5, 3)); // Output: 2

In this example, we augment the math module by adding a subtract function to it.

Conclusion

In this tutorial, we have explored merging and augmenting in TypeScript. Understanding how to extend existing code and avoid naming collisions will enable you to manage your code, improving organization, collaboration, and maintainability.