#Can't check if string is corresponding to an enum value

7 messages · Page 1 of 1 (latest)

digital obsidian
#

Hi! For some reason I can't verify if a string "in" an enum / corresponding to an enum value.

I have the following enum:

export enum Command {
    RUN = "run"
}

And the following code checking the string:

import { Command } from "./command.enum.ts"

const str = "run"

console.log(str in Command) // returns false
console.log(str.toUpperCase() in Command) // returns false
console.log((<any>Object).values(Command).includes(str))  // returns false
console.log((<any>Object).values(Command).includes(str.toUpperCase())  // returns false
console.log((<any>Object).keys(Command).includes(str))  // returns false
console.log((<any>Object).keys(Command).includes(str.toUpperCase())  // returns false

How do i check if a string is in an enum properly?

bright siren
#

"properly"? you don't. enums are meant to be opaque. you may want a different structure

#

perhaps an array, if you want to check for valid values.

#

not sure why you're saying they're all false though

#

Command is effectively { RUN: "run" } there

lethal riverBOT
#
that_guy977#0

Preview:```ts
enum Command {
RUN = "run"
}

const str = "run"
console.log(Command)
console.log(str in Command) // returns false
console.log(str.toUpperCase() in Command) // returns false
console.log(Object.values(Command).includes(str)) // returns false
console.log(Object.values(Command).includes(str.toUpperCase())) // returns false
...```

digital obsidian