1

Since TypeScript 1.8 you can create a string literal type to define the type and an object with the same name for the list of values. It mimics a string enum's expected behaviour (based on David Sherret answer on Create an enum with string values in Typescript), like:

type MyStringEnum = "member1" | "member2";

const MyStringEnum = {
    Member1: "member1" as MyStringEnum,
    Member2: "member2" as MyStringEnum
};

I have a need of ExtendedMyStringEnum which would limit types to all MyStringEnum's types and add another. So I do this:

type ExtendedMyStringEnum = MyStringEnum | "member3";

const ExtendedMyStringEnum = {
    Member3: "member3" as ExtendedMyStringEnum
};

It all works fine, except that I'd like to be able to access all 3 members - Member1, Member2 and Member3 via ExtendedMyStringEnum, like:

ExtendedMyStringEnum.Member1
ExtendedMyStringEnum.Member2
ExtendedMyStringEnum.Member3

That would be more comfortable for the users (I think) and, if I'd need to loop through all the properties, I would only need to do for ExtendedMyStringEnum instead of both MyStringEnum and ExtendedMyStringEnum. Is this doable?

Community
  • 1
  • 1
zeroin
  • 5,863
  • 6
  • 31
  • 42

0 Answers0