I have an enum containing some arbitrary values and want to automatically map the values of the enum to another enum 1-to-1 (with some arbitrary addition). What would be the most idiomatic way to accomplish this task?
I want to do something like add Element.keys+"Magic" to the Skills enum in a declarative fashion and then have these values available as keys without needing to duplicate the work and add a suffix.
enum Element {
Air,
Fire,
Earth,
Water
}
-->
enum Skills {
// Unrelated Skills
Unarmed,
LightArmor,
etc. . .
// 1-to-1 Mapping
AirMagic,
FireMagic,
EarthMagic,
WaterMagic
}
Answering my own question in case others are looking to accomplish something similar. . .
While it doesn't seem to be possible to accomplish this task with enums, I have managed something in the same spirit with 'Template Literal Types'.
type Element =
| "Air"
| "Fire"
| "Earth"
| "Water";
type Skills =
| "Unarmed"
| "LightArmor"
| `${Element}Magic`;
This yields a string union type like so: "Unarmed" | "LightArmor" | "AirMagic" | "FireMagic" | "EarthMagic" | "WaterMagic"
Resources
https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html
https://www.typescriptlang.org/play?#code/C4TwDgpgBAogNhAthAdsAKuaBeKAiAQQEsAnPKAH3wDFSJyq8YBDE4ACwfwHVngIyAbgCwAKDGhIUAMoBrInDgBnKLjwBVFK2QATLngAyRAObtgBEogD2ZSlAAGAEgDe8JKgxYAvgFlmxogBjexFxUQAzAFcUQOAiKxQofiVgAAoleUUALhlM5QBKKGcxKChAhKUrBAA6OCtjdLz8sS8xMQB6dqhMKWYoFJIiFGModgFocJsoZkjgK3LEMAQ4hOqJCBTUwlI-AMC8ZrCgA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With