0

Using Typescript I want to convert Enum to

type keys = "key1"| "key2"
// or
type values = "value1" | "value2"

I can do it with class

class C { a: number; b: string;}
type Keys = keyof C; // "x" | "y"
type Values = C[keyof C]; // string | number

What I would like to do

enum Roles {Admin = "admin", Client = "client"};
? --> type Keys = ...; // "Admin" | "Client" 
? --> type Values = ...; // "admin" | "client"; 

That could be a little helpful

enum Roles {Admin = "admin", Client = "client"};

type values = {[K in Roles]: K}  // { admin: Roles.Admin; client: Roles.Client; }
j3ff
  • 5,719
  • 8
  • 38
  • 51

2 Answers2

1

Using enum I am not sure how to do it, but you can achieve what you want using a type :

type RolesType = { Admin: "admin", Client: "client"}

type Keys = keyof RolesType    // "Admin" | "Client"
type Values = RolesType[Keys]  // "admin" | "client"
JeromeBu
  • 1,099
  • 7
  • 13
0

While you can pretty easily get the enum keys as keyof typeof Roles (it's pretty well explained here), unfortunately it's impossible to get the enum values union type. See this answer of a similar question for more details. A workaround might be to use an Object instead of the enum as JeromeBu suggested:

type Roles = { Admin: "admin", Client: "client" };
type Keys = keyof Roles;
type Values = Roles[Keys];
Valeriy Katkov
  • 33,616
  • 20
  • 100
  • 123