Mapping Enum to Type of keys or values

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; }

Upvotes: 0

Views: 328

Answers (2)

Valeriy Katkov
Valeriy Katkov

Reputation: 40612

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];

Upvotes: 0

JeromeBu
JeromeBu

Reputation: 1159

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"

Upvotes: 1

Related Questions