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.
// 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