-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Enum value lookup by string variable should be typed as the enum type. #592
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
Comments
We don't do this on purpose because of this: var s = "1";
var fromS = Letter[s]; // Runtime value is string, not Letter If you really actually know that the value you're indexing with is a string key in the enum, use a type assertion. |
Additionally, the way we would enforce this kind of constraint in the type system would be by giving enum's an implicit string indexer that returns the enum type. But this would make it very difficult to add additional members to the enum via a merged module. |
@RyanCavanaugh Now that we have string literal types and union types, couldn't this be improved somewhat? |
@masaeedu which parts specifically? |
Just spitballing here, but maybe you could automatically generate a union string literal type composed of all the entries in the enum. Any string assignable to that type produces a number, any other string produces |
You're aware that |
Or you're talking about the case where you have |
@RyanCavanaugh Yeah, that one. That lets users dynamically pick the string, but still get the correct type. |
Low priority, I know, but if you think it has a shot I could open an issue and attempt a PR. |
I think we're already tracking this (essentially) at #6080. Instead of special-casing enums, we can just say that indexing |
I'm trying to map a value in a JSON blob that is serialized as a string to application logic code in TypeScript where the value is logically one of a set of values (and then map that back to JSON as a string to send back to a server). Naturally this maps quite well to enums. However, the type of enum value lookups via string variables is inferred as
any
whereas I would expect it to be the type of the enum. Here's an example:I propose that a change be made so that member access of an enum 'type' via a variable typed as string should be an expression with a value that is that enum 'type'.
Some more examples of what I would expect
The text was updated successfully, but these errors were encountered: