3

Suppose I have this const enum definition:

const enum Snack {
    Apple = 0,
    Banana = 1,
    Orange = 2,
    Other = 3
}

In my typescript code, can get the string literal of one of the members?

In C# it would be e.g. nameof(Snack.Orange). (I know that nameof isn't supported by typescript and I known how it's possible for non-const enums.)

1 Answer 1

6

By default const enums are completely removed at compile time, so there is no runtime object that represents the enum. You can use preserveConstEnums to force the enum object to be generated. The problem is the compiler will still not allow you to access the enum object, so you have to use a work around to access the enum.

With preserveConstEnums turned on, we can put the enum in a namespace:

namespace enums {
    export const enum Snack {
        Apple = 0,
        Banana = 1,
        Orange = 2,
        Other = 3
    }
}
let enumName = (enums as any).Snack[enums.Snack.Apple];

Or if the enum is within a module:

export const enum Snack {
    Apple = 0,
    Banana = 1,
    Orange = 2,
    Other = 3
}

let enumName = (exports as any).Snack[Snack.Apple];

If you don't want to use this flag, you can create an object that will by it's definition have to contain all the members of the enum, and you can search this object for the name. Given that you will get a compile time error on this object if you add or remove anything from the enum this might be a usable work around:

let SnackNames : { [P in keyof typeof Snack]: { Name: P, Value: typeof Snack[P] } } = {
    Apple : { Value: Snack.Apple, Name: "Apple" },
    Banana : { Value: Snack.Banana, Name: "Banana" },
    Orange : { Value: Snack.Orange, Name: "Orange" },
    Other : { Value: Snack.Other, Name: "Other" },
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.