How do I a union type of string values from an enum?

Viewed 1806

I have an enum like this

enum A {
  Car = "car",
  Bike = "bike",
  Truck = "truck"
}

and I want to get a type that is car | bike | truck

I know that keof typeof A can give me Car | Bike | Truck but I need the values here as opposed to keys.

1 Answers

As far as I'm aware what you're trying to do here isn't possible with enums, unfortunately.

If you don't have to make use enum you can work around this by using an object to hold the values of your type and use const assertions (only if you're using TypeScript 3.4+) to create a type based on the keys and values which acts as an enum-like type.

Example:

const A = {
  Car: "car",
  Bike: "bike",
  Truck: "truck",
} as const;

type A = typeof A[keyof typeof A];

const x: A = A.Bike; // A.Car, A.Bike, A.Truck
const y: A = "bike" // "car", "bike", "truck"
Related