Advertisement
Intermediate TypeScript, Namespaces & Declaration Merging

How does merging work between a namespace and a class (or function) sharing the same name?

Short answer

A namespace can merge with a class, function, or enum of the same name declared alongside it, effectively attaching static-like members or nested types to that class/function/enum — this pattern was TypeScript's original mechanism for expressing things like static-nested-types…

Save TypeScript mock interview
Advertisement
AModel answer
A namespace can merge with a class, function, or enum of the same name declared alongside it, effectively attaching static-like members or nested types to that class/function/enum — this pattern was TypeScript's original mechanism for expressing things like static-nested-types before more modern syntax existed.
class Album {
  title: string = '';
}
namespace Album {
  export function create(title: string): Album {
    const a = new Album();
    a.title = title;
    return a;
  }
}
Album.create('OK Computer'); // uses the merged namespace member
Real-world example
Attaching a static factory-like namespace of helper functions directly onto a class, without those helpers being instance methods.
Likely follow-ups
  • Is this class-namespace merging pattern still commonly recommended in modern TypeScript?
Related topics