KarloX
KarloX

Reputation: 987

TypeScript: Get member name of const enum as a string?

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.)

Upvotes: 3

Views: 5216

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249716

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" },
}

Upvotes: 6

Related Questions