0

I have an enum that needs to remain as a number enum - so i can't change it to a string.

I would like to cast a string to the correct enum without doing a long switch :-)

for example, here is my enum

export enum LogLevel {
  TRACE = 0,
  DEBUG = 1,
  INFO = 2,
  LOG = 3,
  WARN = 4,
  ERROR = 5,
  FATAL = 6,
  OFF = 7
}

I get a string passed to me, lets say the string is "WARN" that I need to have a variable that is equal to

LogLevel.WARN

Casting between strings and enum strings is easy but no so easy when I need to keep the enum as a numbered enum.

Any ideas the best way of doing this?

Thanks in advance

** EDIT **

Actaully its a compiler error showing the following

TypeScript TS7015 error when accessing an enum using a string type parameter

There is a fix here

https://github.com/Microsoft/TypeScript/issues/17800

    let s: string = "WARN"
    console.log(LogLevel[s as keyof typeof LogLevel]) // 4
Ian Gregson
  • 397
  • 4
  • 13

1 Answers1

2

Enums are available as a runtime construct, you can index into the enum using a string:

let s: string = "WARN";
console.log(LogLevel[s]); // 4

On the playground.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Thanks, yes it was a TS7015 error, but after you confirming it was the correct way - it lead me to look why. So accepting your answer thanks! I updated my answer – Ian Gregson Jun 16 '19 at 10:47
  • @IanGregson - Gotcha. Are [this question's answers](https://stackoverflow.com/questions/36316326/typescript-ts7015-error-when-accessing-an-enum-using-a-string-type-parameter) relevant? I wonder if we should mark this a duplicate of that. – T.J. Crowder Jun 16 '19 at 10:51