Issue
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
Solution
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
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.