Indexed access lookup on enum type could produce specific key types
See original GitHub issueSuggestion
Per the documentation, it is possible to reverse map an enum at runtime:
enum Enum {
A,
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"
However, suppose we wanted to get the type of the enum name from the enum value at compile time. That is, get some type T = "A"
from Enum.A
. From the example above, we would expect something like the following to work:
type T = typeof Enum[Enum.a]; // evaluates to string rather than "A"
const A: T = "A"; // compiler has no issues
const B: T = "B"; // compiler has no issues
As written above, the compiler fails to get the correct type. However, I have found a workaround:
type T = keyof { [K in keyof typeof Enum as typeof Enum[K] extends Enum.A ? K : never]: any }; // evaluates to "A"
const A: T = "A"; // compiler has no issues
const B: T = "B"; // compiler now throws a fit as expected
It would be nice if this could be abstracted away from the developer.
Issue Analytics
- State:
- Created a year ago
- Reactions:4
- Comments:10 (5 by maintainers)
Top Results From Across the Web
Documentation - Indexed Access Types - TypeScript
Indexed Access Types. We can use an indexed access type to look up a specific property on another type: ts. type Person =...
Read more >Using an enum as a dictionary key - typescript - Stack Overflow
How can I create a lookup type for an enum that guarantees every value of the enum will lead to another value of...
Read more >The trouble with TypeScript enums - Thoughtbot
In TypeScript, enums have a few surprising limitations. In particular, it can be challenging to check whether or not a value is in...
Read more >TypeScript string enums, and when and how to use them
No matter how much you know about TypeScript enums, this guide covers all the best practices for using string-based enums in production.
Read more >enum — Support for enumerations — Python 3.11.1 ...
uses index syntax to return members by name ... Even though we can use class syntax to create Enums, Enums are not normal...
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
Well, fair 😅
@RyanCavanaugh I kind of get the impression this issue counts as that proposal (and you tagged it
Declined
😉).