0
export enum Animals {
        Cow,
        Pig
    }

I have a function receiving an Enum:

export function printEnumName(Enum: any) {
 console.log(someFancyFunctiontoPrintMyEnumName(Enum)); //It should print the enum's name "Animals"
}

I want to implement that fancy function to avoid sending it by parameter.

EDIT: I don't want to print the variables from Animals, like I mentioned on the commented line (also on the post's title) on the console log I want to print "Animals" the enum's name not the enum's variables on the function that is receiving Animals as a parameter. I tried to print using this approach but It didin't work:

    export function printEnumName(Enum: any) {
        for (let element in this.printEnumName) {
            console.log(element); //It would be nice to print "Animals" literally animals 
        }
}
IBot
  • 356
  • 3
  • 20

2 Answers2

0

They have good description for enums https://www.typescriptlang.org/docs/handbook/enums.html.

Just access enum key.

Animals.Cow

To get names, try

  Object.keys(Animals).filter((v) => {
      return isNaN(parseInt(v));
   });
Vayrex
  • 1,417
  • 1
  • 11
  • 13
  • But seems it is duplicate https://stackoverflow.com/questions/18111657/how-does-one-get-the-names-of-typescript-enum-entries – Vayrex Mar 28 '18 at 22:32
  • It's not duplicate since I don't want to print the variables names inside the enum... – IBot Mar 29 '18 at 10:43
0

It's helpful to look at what the enum becomes after transpiling to JavaScript:

var Animals;
(function (Animals) {
    Animals[Animals["Cow"] = 0] = "Cow";
    Animals[Animals["Pig"] = 1] = "Pig";
})(Animals || (Animals = {}));

Animals becomes a regular variable. To get its name, you can apply any method you'd apply to get a variable name in JavaScript, for example Object.keys({Animals})[0].

For more discussion on the subject: Variable name as a string in Javascript

lanterlog
  • 23
  • 4
  • I do not want to print the variables inside animals, I want to print Animals on the function printEnumName @lanterlog – IBot Mar 29 '18 at 10:42
  • The code I posted is not code to print anything, it just illustrates that Animals is a regular variable. I have now added an example solution that will print `"Animals"` to clarify. – lanterlog Mar 30 '18 at 11:46