Advertisement
Intermediate TypeScript, Namespaces & Declaration Merging

How do you merge a namespace with an enum to add extra static-like helper functionality to that enum?

Short answer

Declare a namespace with the same name as the enum, and add exported functions inside it — TypeScript merges the namespace's members onto the enum object, letting you attach utility functions (like validation or display formatting) directly to the enum's name.

Save TypeScript mock interview
Advertisement
AModel answer
Declare a namespace with the same name as the enum, and add exported functions inside it — TypeScript merges the namespace's members onto the enum object, letting you attach utility functions (like validation or display formatting) directly to the enum's name.
enum Color { Red, Green, Blue }
namespace Color {
  export function isValid(value: number): boolean {
    return value in Color;
  }
}
Color.isValid(1); // true, uses the merged namespace function
Real-world example
Adding a helper function like isValid() or toDisplayName() directly onto an enum's own namespace, rather than as a separate standalone function.
Likely follow-ups
  • Would this same merging capability work if you tried to merge a namespace with a 'const enum' instead?
Related topics