Glossary / Declaration merging

Declaration merging

Declaration merging is a TypeScript feature that combines multiple declarations with the same name into one type-level entity. It supports patterns such as augmenting interfaces, adding members to library types, and describing JavaScript APIs assembled from multiple declarations; it does not merge or modify runtime objects.

What can merge

Interfaces with the same name merge their members. Namespace declarations can merge with certain classes, functions, or enums to add static-like type members. Module augmentation can extend declarations for an existing module. Not all declaration kinds merge: duplicate type aliases or incompatible duplicate variables generally produce errors. Overload declarations merge with ordering rules that can affect overload resolution.

declare module 'some-library' {
  interface Options {
    traceId?: string;
  }
}

This augmentation changes TypeScript's model only. If the runtime library does not actually accept traceId, the declaration creates an unsound contract. Augmentation scope and module resolution are sensitive to whether a file is a script or module and how the target package exports its declarations.

Engineering guidance

Use merging when extending a third-party type intentionally and keep runtime implementation aligned. Prefer local wrapper types or upstream contributions over broad ambient augmentations that affect an entire program. Add compile-time fixtures for augmented APIs and ensure the augmentation is included for consumers. Avoid duplicate declaration files that silently widen or conflict with public contracts.

Interview questions

  1. Does declaration merging alter runtime? No, it changes only the compile-time model.
  2. Can interfaces merge? Yes; same-name interface members combine subject to compatibility rules.
  3. Can type aliases merge? No, duplicate aliases conflict.
  4. What is module augmentation? Extending an existing module's type declarations from another declaration.
  5. Why is augmentation dangerous? It can claim runtime capabilities that do not exist or globally affect unrelated code.

References