-
Notifications
You must be signed in to change notification settings - Fork 12.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enum with special numbers overwrites own value #48956
Comments
Interestingly, the following is an error, likely because it would otherwise suffer from the same issue: enum Fooey { "0", "1", "2" };
// TS2452 - An enum member cannot have a numeric name. edit: oops, you already mentioned this |
Wow, I love this edge case. FYI, what you're calling "lookup" is known as a reverse mapping. |
Woops yes wrong terminology on my part. I was getting the terminology from this SO post https://stackoverflow.com/questions/28818849/how-do-the-different-enum-variants-work-in-typescript |
#56161 has been reverted. |
Bug Report
🔎 Search Terms
Enum number computed overwrite Infinity NaN
🕗 Version & Regression Information
I noticed on 4.6.2, but using TS Playground am able to reproduce on earliest possible version (3.3.3). Also still occurs on nightly build.
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
Typescript generates the following code for that enum using a "lookup object":
As a result, the Computed enum actually has values of Strings, rather than the "computed" numbers as expected
Note the "lookup object" behavior itself is not unexpected, but the side effect of overwriting keys is unexpected.
🙂 Expected behavior
Typescript should not overwrite an existing key with a new value. Most likely that would mean disabling the "lookup values" for computed.
Extra Discussion
This does not impact
const enum
because values likeInfinity
are considered "computed".It is also possible to do something like
with similar results.
The latest versions of typescript warn at this behavior, but it is possible to compile and I don't think it warns on all versions. But I omitted from core issue for that reason.
Similarly
has similar behavior (when compiled) but TS does warn about numeric names (I believe this warning occurs in all versions).
It does not occur when using string enums, as those never write "lookup objects"
Effectively this issue happens whenever the
String(val)
(generally.toString()
internally) returns a key in the Enum.Possible solutions:
1 + 2
are "computed" but are resolved at compile time. So maybe "computed" where the value is anything but a number literal.NaN
,Infinity
or-Infinity
as an enum key name. There may be others I am not aware of right now... but I was not able to reproduce error with exponential notation likeNumber.EPSILON
("An enum member cannot have a numeric name.")The text was updated successfully, but these errors were encountered: