Open In App

How to Access Enum Values in TypeScript ?

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Examples of Accessing Enum Values in TypeScript

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.

Syntax:

const enumValue = EnumName['EnumKey'];

EnumName is the name of the enum.
EnumKey is the key of the enum whose value we want to access.

Example: The code below demonstrates how we can use the bracket notation to access enum values in typescript.

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

// Access Enum using bracket notation
let key: keyof typeof GFG = "Org";
let value = GFG[key];

console.log(value);

Output:

GeeksForGeeks

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.

Syntax:

const enumValue = EnumName.EnumKey;

EnumName is the name of the enum.
EnumKey is the key of the enum whose value we want to access.

Example: The code below demonstrates how we can use the DOT notation to access enum values in typescript.

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

// Access Enum using DOT notation
let value1 = GFG.Org;
let value2 = GFG.Founder;
let value3 = GFG.Est;

console.log(value1);
console.log(value2);
console.log(value3);

Output:

"GeeksforGeeks"
"Sandip Jain"
"2009"

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.

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 = "GeeksForGeeks",
    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:

GeeksForGeeks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads