Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we avoid the repetition of String enum value?

I’m using this code:

type Group = {
  [key in ROLES]?: string;
};

enum ROLES {
  simple = "simple",
  admin = "admin",
}

Is there a way to avoid the "repetition" of simple = "simple"/admin = "admin"?

Can we have simply:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enum ROLES {
  simple,
  admin,
}

>Solution :

Yes, the enum you declared is valid TypeScript. But instead of strings, this enum contains numbers and is equivalent to:

enum ROLES {
  simple = 0,
  admin = 1,
}

But you can still extract the key names from ROLES to build the Group type.

type Group = {
  [key in `${keyof typeof ROLES}`]?: string;
};

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading