2

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Joji
  • 4,703
  • 7
  • 41
  • 86
  • Don't you just want... `A`? That's the type that means any of the values of the enumeration. – jonrsharpe Sep 05 '20 at 21:09
  • What are you trying to do? I would probably just ditch enums and use `'car' | 'bike' | 'truck'` in the first place. – Roberto Zvjerković Sep 05 '20 at 21:25
  • This has a thorough explanation of why it's not possible: https://stackoverflow.com/questions/50376977/generic-type-to-get-enum-keys-as-union-string-in-typescript However, like the 2 guys above me, I also believe that what you're trying to achieve can be done without a union of values. Can you specify what it is? – Ridiculous Sep 05 '20 at 21:43

1 Answers1

6

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"
undefined
  • 308
  • 1
  • 8
  • thanks for the reply. I am not sure when I should use `enum` vs. a const object. I just need a way to reference some hardcoded string but I thought `enum` is good for that. – Joji Sep 06 '20 at 20:48
  • `enum` is a great way to handle values that can be one of a specific set of cases, whereas if you're just looking for a way to restrict a type to be a series of specific values and don't need a "pretty" way to refer to the values through keys I would look at just creating a union type as was suggested in a reply to your initial question. e.g. `type A = "car" | "bike" | "truck"` I would only implement my example if you needed to refer to the key at a later point in the code. – undefined Sep 06 '20 at 21:10