Given:
type Color = "red" | "blue" | "green"
I want to enable client code like:
console.log(Colors.red)
Obviously I could create:
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"