Typescript string enum reverse mapping

In this typescript tutorial, we will see what is an enum and string enum. Also, we will see how to do reverse mapping for string enums.

The topics we are going to cover:

  • What is an enum in typescript?
  • What is a string enum in typescript
  • How to do string enum reverse mapping in typescript

What is an enum in typescript?

An enum in TypeScript is a unique data type that allows us to create a set of named constants. A list of constant values may be included in an enum, and a distinctive identifier may be given to each item i.e. string or number.

There are three different forms of enum are there:

  • String enum
  • Numeric enum
  • Heterogenous enum (contains both string and number)

What is a string enum?

In TypeScript, an enum form called a string enum has values that are strings rather than numbers. A string enum, like a standard enum, enables us to provide a collection of named constants, but instead of dynamically incrementing the values, you directly assign string literals to them.

Example of String enum in typescript

enum Country {
    USA = "usa",
    UK = "uk",
    Australia = "australia",
  }
  
  let myFruit: Country = Country.USA;
  console.log(myFruit); // Output: "usa"
  console.log(Country.UK); // Output: "uk"

How to do reverse mapping of string enum

Here we will see how to do a reverse mapping to a string enum in typescript.

Reverse mapping in TypeScript means having the option to look for an enum value using the string literal that corresponds to it.

When we declare an enum in typescript by default, the string values are implicitly given numeric values (start from 0, and increment by 1 each time). For example

enum Country {
    USA, //0
    UK, //1
    Australia, //2
  }

These enum values can be used in the code as follows:

let selectedCountry: Country= Country.UK;
console.log(selectedCountry); // Output: 1

But, occasionally you might wish to carry out a reverse mapping and look up the enum value using its text literal value. This is particularly helpful if your user interface enables end users to choose an enum value by its string name.

For example, we can declare an enum in typescript with values that are string literals like below:

enum Country {
    USA = "usa",
    UK = "uk",
    Australia = "australia",
  }

By defining a function that accepts a string value as input and outputs the related enum value, we can then conduct a reverse mapping in typescript:

enum Country {
    USA = "usa",
    UK = "United Kingdom",
    Australia = "australia",
}

function getCountry(value: string): Country | undefined {
    if (value === "usa") {
        return Country.USA;
    } else if (value === "uk") {
        return Country.UK;
    } else if (value === "australia") {
        return Country.Australia;
    } else {
        return undefined;
    }
}

let myCountry: Country | undefined = getCountry('uk');
if (myCountry !== undefined) {
    console.log(myCountry); // Output: undefined
} else {
    console.log("Country not found.");
}

In the above reverse mapping example, we define a function called ‘getCountry’, which executes the reverse mapping of the Country enum

When we call the getCountry(), with a string value like ‘uk’, and it will return the enum value of Country.UK.

To compile the above code, run the below command and you can see the below result.

ts-node enumReverseMapping.ts
Typescript string enum reverse mapping
Typescript string enum reverse mapping

Another way we can do reverse mapping of string enum is by using type assertation to cast a string value to an enum value.

enum Country {
    USA = "usa",
    UK = "uk",
    Australia = "australia",
  }
  
  function getCountry(value: string): Country | undefined {
    const enumKey = Object.keys(Country).find(
      (key) => Country[key as keyof typeof Country] === value
    );
    if (enumKey !== undefined) {
      return Country[enumKey as keyof typeof Country];
    }
    return undefined;
  }
  
 console.log(getCountry("usa")); // Output: Country.USA
  console.log(getCountry("uk")); // Output: Country.UK
  console.log(getCountry("australia")); // Output: Country.Australia
  console.log(getCountry("canada")); // Output: undefined
  

In the above code, Country is defined as an enum, with three values, and define a function as getCountry takes a value as a string and returns the corresponding value of the ‘Country’ enum.

The function works by using object.keys to get an array of the keys of the Country object and then using the find method to get the key whose value matches the input string.

If a matching key is found, the function will return the value corresponding to the Country enum. Else it returns ‘undefined’.

To compile the code and run the below command and you can see the resulting console.

 ts-node enumReverseMapping.ts
 string enum reverse mapping in Typescript
string enum reverse mapping in Typescript

This is how we can perform string enum reverse mapping in Typescript.

Conclusion

In this typescript tutorial, we saw what an enum is, also, we understand what string num is in typescript. Then we saw how we can perform string enum reverse mapping in typescript.

  • What is an enum in typescript?
  • What is a string enum in typescript
  • How to do string enum reverse mapping in typescript

You may also like:

>