Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get TypeScript enum name from instance

I have the following TypeScript enum:

enum Country {
    BR = "Brazil",
    NO = "Norway"
}

Then imagine I have a method that takes a Country as an argument, like so:

someFunc = (country: Country): void => {
    console.log(country) //Will print "Brazil" if country = Country.BR
    console.log(Country[country]) //Same as above
    console.log(???) //I want to print "BR" if country = Country.BR
}

How do I solve the third console.log statement?

How do I get a hold of the enum key?

Regards

like image 905
Robin Jonsson Avatar asked Jan 16 '18 07:01

Robin Jonsson


People also ask

How do I get all enum names?

Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);

How do I get all the enum values in TypeScript?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) .

Can I use enum as a type in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.


1 Answers

Under the enum constrution you get something like this

Country["BR"] = "Brazil";
Country["NO"] = "Norway";

which is a simple object.

By default you can't get the keys of your enum. But you can iterate over the keys manually and try to find that one.

enum Country {
    BR = "Brazil",
    NO = "Norway"
}

console.log(Object.keys(Country).find(key => Country[key] === country))
like image 102
Suren Srapyan Avatar answered Sep 22 '22 00:09

Suren Srapyan