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
1
  • 1
    Did you try using the string as an index? Like this LogLevel[str] Commented Jun 16, 2019 at 10:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
@IanGregson - Gotcha. Are this question's answers relevant? I wonder if we should mark this a duplicate of that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.