Open
Description
Suggestion
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.