How to use Object Lookup In Typescript

Another approach involves using object lookup, which utilizes a mapping object to access enum values. This method offers flexibility and ease of use, especially in scenarios where dynamic key-value pairs are required.

Syntax:

const enumValue = EnumLookup[EnumKey];

EnumLookup: An object containing enum keys as properties and their corresponding values.
EnumKey: The key of the enum whose value we want to access.

Example: In this example we are following above explained approach.

JavaScript
// Define Enum
enum GFG {
    Org = "w3wiki",
    Founder = "Sandip Jain",
    Est = "2009"
}

// Create lookup object
const enumLookup = {
    Org: GFG.Org,
    Founder: GFG.Founder,
    Est: GFG.Est
};

// Access Enum using Object Lookup
let enumKey: keyof typeof GFG = "Org";
let value = enumLookup[enumKey];

console.log(value); 

Output:

w3wiki


How to Access Enum Values in TypeScript ?

Enums in TypeScript allow us to define a set of named constants. In this article, we will see how we can access enum values in typescript using different approaches which are as follows:

Table of Content

  • Using bracket notation
  • Using DOT notation
  • Using Object Lookup

Similar Reads

Examples of Accessing Enum Values in TypeScript

Using bracket notation...

Using bracket notation

In this approach, we are using the bracket notation to access enum values in typescript. By using the enum name and the desired key within the square bracket we can access the enum value associated with that key....

Using DOT notation

In this approach, we are using the dot notation to access enum values in typescript. It involves directly referencing the enum name followed by the enum member name (key) using a dot (.) syntax....

Using Object Lookup

Another approach involves using object lookup, which utilizes a mapping object to access enum values. This method offers flexibility and ease of use, especially in scenarios where dynamic key-value pairs are required....

Contact Us