14

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

5 Answers 5

18

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))
Sign up to request clarification or add additional context in comments.

5 Comments

But that means making an if statement for all possible values?
Why if statements? You can just compare with your country
It's not very flexible... Say I have 100 enum values inside my Country enum, and my method would like to print the country code (key of the enum) for a given enum instance. Then there's no solution for this?
Country[key] === country) this statement will work for every country. It just gets the key of that enum. If I understood you correct.
Ah yes, that works indeed! Was hoping there was a more simple solution for this
4

ts-enum-util (github, npm) supports reverse lookup of value->key for string enums, compile time type safety, and run-time validation.

import {$enum} from "ts-enum-util";

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

someFunc = (country: Country): void => {
    // throws an error if the value of "country" at run time is
    // not "Brazil" or "Norway".  
    // type of "name": ("BR" | "NO")
    const name = $enum(Country).getKeyOrThrow(country);
}

Comments

0

First you need to understand what is the js code for

enum Country {
    BR = "brazil",
    NO = "norway"
}

Its simply

var Country;
(function (Country) {
    Country["BR"] = "brazil";
    Country["NO"] = "norway";
})(Country || (Country = {}));

So basically it's an object with "BR" and "NO" as keys. and assuming we know how to find key from value in object. Check this . Using same

enum Country {
    BR = "brazil",
    NO = "norway"
}

namespace Country {
    export function getEnum(c: string): Country | undefined {
        if(!c) return undefined;
        const cLowerCase = c.toLowerCase();
        return Object.keys(Country).find(k => Country[k as keyof typeof Country] === cLowerCase) as Country
    }
}


console.log(Country.getEnum('test'))

console.log(Country.getEnum('Brazil'))

console.log(Country.getEnum('norway'))

If you are wondering why we used keyof typeof check this answer

In case you have lots of keys in enum you can use map to store reverse mapping and use that

Comments

0

I made this "generic" version


enum AccountType {
  Google = 'goo',
  Local = 'cal',
  Facebook = 'boo',
  Twitter = 'x',
  LinkedIn = 'ink'
}

function getEnumName<T> (enumType: Record<string, number|string>, value: T) {
  return Object.entries(enumType).find(([k,v] ) =>  v === value )?.[0];
}
 
console.log(getEnumName(AccountType, AccountType.Twitter));

Comments

-1

I often use a plain JavaScript object instead of an enum, and use the keyof operator for type safety on its keys:

const CountryMap = {
    BR: "Brazil",
    NO: "Norway"
};

// equivalent to: type Country = 'BR' | 'NO';
type Country = keyof typeof CountryMap;

const someFunc = (country: Country): void => {
    console.log(country);
}

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.