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