1

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?

3
  • 1
    Color.GREEN is 1 and Color.RED is 0, they're not the strings "GREEN" and "RED". You'll see that if you log these values or your Map.Color[Color.RED] is "RED" Commented Dec 1, 2022 at 10:58
  • @NickParsons: I do not pass a string to .get(). The type of myColor is Color. And the map is declared with keys of type Color. How can I make this work? Commented Dec 1, 2022 at 11:05
  • 2
    Sean's answer explains what's going on well and how it can be fixed Commented Dec 1, 2022 at 11:10

1 Answer 1

3

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"];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It is really confusing if we declare myColor with type Color, but really it is not.
No problem. The compiler would have thrown an error when you initially tried to cast red_s as Color. But then you added the as unknown to get around the error. This should generally be avoided!

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.