Querying Enums containing string initializers with a variable throws TS7015
See original GitHub issueTypeScript Version: 2.4.2
Code
enum Colors {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
const test: string = 'Red';
Colors[test];
Workaround
enum Colors {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
const test: any = 'Red';
Colors[test];
Expected behavior: Should compile
Actual behavior:
error TS7015: Element implicitly has an ‘any’ type because index expression is not of type ‘number’.
There is an issue #11773 demonstrating it with a “normal” enum.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:5 (2 by maintainers)
Top Results From Across the Web
TypeScript TS7015 error when accessing an enum using a ...
Because enumKey is an arbitrary string , TypeScript doesn't know whether enumKey is the name of a member of State , so it...
Read more >error ts7015: element implicitly has an 'any' type because ...
microsoft/TypeScriptQuerying Enums containing string initializers with a variable throws TS7015#17800. Created over 5 years ago.
Read more >TypeScript string enums, and when and how to use them
Specifying enum member values Values are initialized implicitly via number literals, or explicitly via string literals. Constant enum members: ...
Read more >guarding on enum value
public func email(invoice: Invoice) throws { guard case . ... emailStatus else { // ERROR: "Variable binding in a condition requires an initializer"...
Read more >MySQL 8.0 Reference Manual :: 11.3.5 The ENUM Type
An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I found the fix!
const test: keyof typeof Colors = 'Red';
I had the same problem and that fixed it.
Seems we never did anything different with the indexing rules for string enums, which is bad.
Colors[32]
is extremely suspect.