2

Is there a way to get the name of an enum in typescript, like nameof(FirstEnum)? The following code has an ugly if switch that has to be expanded each time a new enum is defined. Is there a more generic way to achieve the same in typescript?

enum FirstEnum {
    First = 0,
    Second = 1,
    Third = 2,
}
enum SecondEnum {
    One,
    Two,
}


function translateEnum(type$, val): string {
    let lookupKey = '';
    if (type$ === FirstEnum) {
        lookupKey = `firstenum.${FirstEnum[val]}`;
    } else if (type$ === SecondEnum) {
        lookupKey = `secondenum.${SecondEnum[val]}`;
    } else {
        throw new Error('not supported');
    }
    //lookupkey example: secondenum.One
    const result = ''; //translate here, ex. await translationService.translate(lookupkey);
    return result;
}

translateEnum(SecondEnum , SecondEnum.One);
0

1 Answer 1

4

Since Typescript Enums are translated to JavaScript objects, you can check if enum key values are members of the enums using the in operator. Note that this only works for enums that are not const and are number-based.

enum FirstEnum {
    First = 0,
    Second = 1,
    Third = 2,
}
enum SecondEnum {
    One,
    Two,
}


function translateEnum(val: FirstEnum | SecondEnum): string {
    let lookupKey = '';
    if (val in FirstEnum || val in SecondEnum) {
      console.log(`Enum value ${val} is valid!`);
      //lookupkey example: secondenum.One
      const result = ''; //translate here, ex. await translationService.translate(lookupkey);
      return result;
    } else {
        console.log(`Enum value ${val} not supported.`);
        throw new Error('not supported');
    }
}

translateEnum(SecondEnum.One);

translateEnum(10);

Output

Enum value 0 is valid!
Enum value 10 not supported.
Uncaught Error: not supported
    at translateEnum (eval at <anonymous> (main-0.js:804), <anonymous>:23:15)
    at eval (eval at <anonymous> (main-0.js:804), <anonymous>:27:1)
    at main-0.js:804

More Information

See stackoverflow question Check if value exists in enum in TypeScript.

Sign up to request clarification or add additional context in comments.

2 Comments

IMHO the asker wants to get "FirstEnum" from the enum FirstEnum. I do not think that is possible though.
Tnx all for the support. I conclude from this answer that it is not possible to get rid of the if statement. I hope this feature will be added soon to typescript, if possible at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.