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…
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 memberReal-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