← Back to TypeScript Course | Chapter 9: Modules and Namespaces | Lesson 5 of 7

Declaration Merging

Declaration merging allows TypeScript to combine multiple declarations with the same name into a single definition. It is commonly associated with interfaces and namespaces and is useful when extending existing type information.

Merging Interfaces

Two interfaces declared with the same name are automatically merged by TypeScript, so their members are combined into a single effective interface rather than one silently overwriting the other.

Example: Merging Interfaces

typescript
interface Box {
  height: number;
}
interface Box {
  width: number;
}
const b: Box = { height: 10, width: 20 };
console.log(b);

Merging Interface Methods

Interface declarations can contribute methods as well as properties to the merged result, so splitting an interface's definition across multiple declarations still produces one complete combined shape.

Example: Merging Interface Methods

typescript
interface Logger {
  log(msg: string): void;
}
interface Logger {
  warn(msg: string): void;
}
const logger: Logger = {
  log: (msg) => console.log(msg),
  warn: (msg) => console.log("WARN:", msg),
};
logger.warn("careful");

Namespace Merging

Namespace declarations sharing the same name can also merge, allowing related members to be added to a namespace incrementally from more than one place in the codebase.

Example: Namespace Merging

typescript
namespace Utils {
  export const a = 1;
}
namespace Utils {
  export const b = 2;
}
console.log(Utils.a, Utils.b);

Namespace and Class Merging

A namespace can merge with a class declaration of the same name, letting exported namespace members act as static-like properties attached to that class.

Example: Namespace and Class Merging

typescript
class Album {
  constructor(public title: string) {}
}
namespace Album {
  export const defaultTitle = "Untitled";
}
console.log(Album.defaultTitle);

Merging and Type Safety

Declaration merging still follows TypeScript's normal type checking rules; all required members from every merged declaration must ultimately be satisfied wherever the merged type is used.

Example: Merging and Type Safety

typescript
interface Config {
  host: string;
}
interface Config {
  port: number;
}
const config: Config = { host: "localhost", port: 8080 };
console.log(config);
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.