0

While trying to do a comparison between a numeric enum, I noticed an error where the enum value is converted to a string type. Is that an expected behavior?

enum Test {
    a = 0,
    b = 1
}

console.log(Test.a === Test[0]);
// ^ This condition will always return 'false' since the types 'Test' and 'string' have no overlap.(2367)

TypeScript version: v4.6.4

Playground Link

2
  • 2
    Test[0] is using the reverse mapping to get "a". Why are you trying to compare them like that? Either you want console.log(Test.a === 0) or console.log("a" === Test[0]), but what you're doing is checking a key against a value. Does that make sense and should I write up an answer? Or am I missing something about your question? Commented May 26, 2022 at 2:26
  • @jcalz oh you are right, I thought it would be comparing two values, but it is indeed different. Commented May 26, 2022 at 17:20

1 Answer 1

2

This seems to be a confusion about what Test[0] is. Numeric enum members in TypeScript get a reverse mapping, where indexing into the enum object with an enum value gives you back the corresponding enum key.

So in

enum Test {
    a = 0,
    b = 1
}

you have Test.a === 0 and therefore Test[0] === "a". And since Test.b === 1, then Test[1] === "b". By comparing Test.a to Test[0], you are comparing a number to a string, and is indeed considered a TypeScript error to make such a comparison.

So you shouldn't write

console.log(Test.a === Test[0]); // error, different types.  Outputs false

But instead possibly one of these:

console.log("a" === Test[0]); // okay, Outputs true
console.log(Test.a === 0); // okay, Outputs true

Playground link to code

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

Comments

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.