Advertisement
Advanced TypeScript, Namespaces & Declaration Merging

How does namespace merging across multiple files work, and what does this mean for organizing large ambient type declarations?

Short answer

Multiple files can each contribute a piece of the SAME namespace (using 'namespace Foo { ...

Save TypeScript mock interview
Advertisement
AModel answer
Multiple files can each contribute a piece of the SAME namespace (using 'namespace Foo { ... }' repeated across files, all included in the compilation), and TypeScript merges all their exported members into one logical namespace — useful for splitting a large set of ambient global types across multiple organized files while still presenting a single unified namespace to consumers.
// file1.d.ts
namespace MyLib {
  export interface Config { name: string; }
}

// file2.d.ts
namespace MyLib {
  export interface Options { verbose: boolean; }
}
// Both Config and Options are accessible as MyLib.Config and MyLib.Options
Real-world example
Organizing a large third-party library's ambient global type declarations across multiple logically-grouped files.
Likely follow-ups
  • What build/inclusion mechanism ensures TypeScript sees and merges declarations spread across multiple .d.ts files like this?
Related topics