Home > OS >  JS: How to convert from string to enum to map key?
JS: How to convert from string to enum to map key?

Time:12-01

Snippet:

enum Color {
    RED = 0,
    GREEN
}

const myMap = new Map<Color, string>([
    [Color.GREEN, "foo"],
    [Color.RED, "bar"]
])


const red_s = "RED"
const myColor: Color = red_s as unknown as Color
console.log(`myColor ${myColor}`)

const mapVal = myMap.get(myColor)
if (mapVal) {
    console.log(`mapVal ${mapVal}`)
}
else {
    console.log(`no mapVal found`)
}

Why is the enum myColor not found in myMap?

How can I use the enum as a key for the map?

CodePudding user response:

The as keyword only tells the compiler to treat a variable as a certain type. It does not actually change the underlying type. If you run a typeof check, you will see myColor is a string, not Color:

const red_s = "RED"
const myColor: Color = red_s as unknown as Color
console.log(`${typeof myColor}`) // Prints string

To set red_s as an enum, you need to do:

const red_s: Color = Color["RED"];
  • Related