Is there a way to easilly create union type from enum in Typescript?

Viewed 51

often when I'm writing Typescript I'm running into situations where I have enum of some sort and from this enum I want to generate union type. I tried looking for utility type which would do it for me but I wasn't able to find any. Is there an easier way of doing so?

enum Person {
  Name = "Adam",
  Age = 32
}

type Something = Person.Name | Person.Age;

I know that this example is rather simple but often I have enums with a tone of entries and doing it by hand is neither enjoyable nor maintainable.

1 Answers

An enum type is itself already equivalent to the union of all members of that enum.

You can even see this in action if you try to use Exclude to remove a member from the enum:

enum Person {
  Name = "Adam",
  Age = 32
}

type Something = Exclude<Person, Person.Age> // Person.Name

Playground Link

Related