1
export enum OperationType {
  HEAL = 1,
  ATTACK
  DEFEND = 20,
  RETREAT,
  // ...plus 30 more values of varying numbers.
};

I have the above numeric enum in TypeScript.

I have a string DEFEND, I want to get the enum equivalent from OperationType with this DEFEND string. Is there a way to get the enum easily and reliably, other than creating a function and manually do a big switch/if-else loop to return the enum itself and maintaining that?

Edit: This is my current code to loop through each of the enums to use it like OperationType["DEFEND"]:

Object.keys(OperationType).filter((v) => isNaN(Number(v))).map((value) => { 
    return <MenuOption onSelect={() => setOperationType(OperationType[value])} text={value} />
})

and I am getting the following error for OperationType[value], Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015).

I am assuming OperationType[value]'s value is failing because it expects a string from key that matches OperationType enums and not just "any" string. Is there a way to fix it?

CyberMew
  • 1,159
  • 1
  • 16
  • 33
  • @HereticMonkey in **C#**? This is typescript – Dimava Apr 22 '23 at 20:34
  • My bad. @Dimava in C# there are several hundred of these types of questions a day, so I'm a bit quick on the trigger. That said, I'm sure there's a dupe for TypeScript too. – Heretic Monkey Apr 22 '23 at 20:37
  • [How do I convert a string to enum in TypeScript?](https://stackoverflow.com/q/17380845/215552) for instance... – Heretic Monkey Apr 22 '23 at 20:38
  • Does this answer your question? [How do I convert a string to enum in TypeScript?](https://stackoverflow.com/questions/17380845/how-do-i-convert-a-string-to-enum-in-typescript) – jsejcksn Apr 23 '23 at 00:07
  • The handbook actually [suggests not using enums](https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums) — example: https://tsplay.dev/wXv6Om – jsejcksn Apr 23 '23 at 00:11

1 Answers1

1

Enums in TS are bidirectional

// compiled code:
export var OperationType;
(function (OperationType) {
    OperationType[OperationType["HEAL"] = 1] = "HEAL";
    OperationType[OperationType["ATTACK"] = 2] = "ATTACK";
    OperationType[OperationType["DEFEND"] = 20] = "DEFEND";
    OperationType[OperationType["RETREAT"] = 21] = "RETREAT";
    // ...plus 30 more values of varying numbers.
})(OperationType || (OperationType = {}));
;

so that's just

let d: OperationType[ /*DEFEND*/ 20 ] // 'DEFEND'
Dimava
  • 7,654
  • 1
  • 9
  • 24