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 I create an object from a union of strings type?

Given:

type Color = "red" | "blue" | "green"

I want to enable client code like:

console.log(Colors.red)

Obviously I could create:

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

const Colors = {
  red: "red",
  blue: "blue",
  green: "green"
}

But that means whenever a color is added I need to do it in two places, which I want to avoid. I know that I could exclude the ‘Colors’ object entirely and just use strings, but I’d like to have it all the same. Is there a way within typescript to generate the Colors object from the Color type, such that modifying Color is all that’s required to make a new color available via Colors.myNewColor in client code?

>Solution :

No, you can’t compute values from types. However, it can be done the other way around. An enum is very suitable for your use case. Then you can define a type based on the enum’s keys dynamically using keyof typeof.

enum Color {
  red = "red",
  blue = "blue",
  green = "green"
}

type Colors = keyof typeof Color;
// type Colors = "red" | "blue" | "green"

TypeScript 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