Skip to content

Indexed access lookup on enum type could produce specific key types #50933

Open
@jfw225

Description

@jfw225

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions