Nested Enums in TypeScript

Today at work I was asked to re-factor some code in our organization’s app that involved replacing a bunch of strings with nested enums. For example, we have a bunch of strings that look something like “ActivityCode.Foo.A” and one of the tech leads wanted me to replace all of these strings with enums. However, you can see from my example string that it isn’t formatted like an enum. An enum would look something like ActivityCode.Foo. But how do you write ActivityCode.Foo.A where there is some nesting going on? The tech lead specifically requested that I use an enum, not an object, which brings us to this blog post: How do you create a nested enum in TypeScript?

Well, the short answer is: You can’t create nested enums in TypeScript.

However, there is a little hack you can use where you can create an object (ActivityCode), which contains a bunch of enums and essentially achieve the same effect. So if you need to write something like ActivityCode.Foo.A using enums, you can write something like:

enum Foo {
A = "ActivityCode.Foo.A",
B = "ActivityCode.Foo.B",
C = "ActivityCode.Foo.C",
}
enum Bar {
A = "ActivityCode.Bar.A",
B = "ActivityCode.Bar.B",
C = "ActivityCode.Bar.C",
}
enum Baz {
A = "ActivityCode.Baz.A",
B = "ActivityCode.Baz.B",
C = "ActivityCode.Baz.C",
}
const ActivityCode = {
Foo,
Bar,
Baz,
};
console.log(ActivityCode.Foo.A);
view raw nestenum.ts hosted with ❤ by GitHub

So there you have it! Pseudo nested enums in TypeScript.

 

topherPedersen