Home > Net >  How do I compose an enum from another enum in Typescript?
How do I compose an enum from another enum in Typescript?

Time:09-06

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
}

CodePudding user response:

Basically you're asking to compose and extend enum with each other, like extending and composing their inner members, at compile time and with simple set operations.

Shortly: you can't.

Since enums are defined at compile time, their set of member is static and can't be derived from other enums. You can have computed members, but that's for the value they hold in.

For you to access the enum and manipulate like you've asked in the question, you'd need access to metaprogramming onto your enums, i.e. using decorators onto them. But that's currently not possible in Typescript.

My advice would be to use a class and / or a type. Refer to this answer for more.

CodePudding user response:

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

  • Related