Declaration Merging
In this page:
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
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
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
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
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
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: