map through enum
See original GitHub issueTypeScript Version: 3.1.6
Search Terms: enum
Code
enum ABC {
A = 'A',
B = 'B',
C = 'C',
}
// No Error
for (const key in ABC) {
console.log(ABC[key]);
}
// Error: Element implicitly has an 'any' type because index expression is not of type 'number'
Object.keys(ABC).map(key => console.log(ABC[key]));
Expected behavior:
Object.keys, values, entries
on enum ABC
infer type of ABC
’s key and value.
Actual behavior:
Cannot get inferred type.
Shouldn’t type of key from enum be ‘A’ | ‘B’ | ‘C’?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:13
- Comments:6 (4 by maintainers)
Top Results From Across the Web
Map Typescript Enum - javascript - Stack Overflow
To map an enum do this: (Object.keys(MyEnum) as Array<keyof typeof MyEnum>).map((key) => {}).
Read more >How to use the map() method with Enums in TypeScript
Use the Object.keys() method to get an array of the enum's keys. · Use the map() method to iterate over the array. ·...
Read more >A Guide to EnumMap - Baeldung
EnumMap is a Map implementation that exclusively takes Enum as its keys. In this tutorial, we'll discuss its properties, common use cases ...
Read more >Using `map()` on JavaScript Enums - Mastering JS
Since a JavaScript enum is just an object, you can iterate over an object using map() and Object.keys() as shown below.
Read more >map through enum #28565 - microsoft/TypeScript - GitHub
I thought string enum doesn't get reverse mapping. This code shows it doesn't. Did i miss something?
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 FreeTop 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
Top GitHub Comments
This is related to, but distinct from, issues like #13254 or #12870.
Usually,
Object.keys(foo)
can’t just returnArray<keyof typeof foo>
, becausetypeof foo
might not completely specify the fields thatfoo
actually has.But
enum
objects are created by the TS compiler and normal code isn’t allowed to add more fields to them. So the exact fields will be known by the compiler.We’ve rejected like 30 PRs trying to change
Object.keys(ABC)
to returnkeyof typeof ABC
. It’s not clear how this would work without some mechanism to traffic through theABC
-ness of thekeys
return value?