![]() |
Enums are a feature in TypeScript that help organize collections of related values. Accessing these values efficiently is crucial for clean, maintainable code. This guide provides a straightforward overview of different methods to access enum values in TypeScript, including bracket notation, dot notation, object lookup, and using Object.entries. Each method is explained with simple examples to enhance your coding techniques. Table of Content Examples of Accessing Enum Values in TypeScriptUsing bracket notationIn 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']; Example: The code below demonstrates how we can use the bracket notation to access enum values in typescript.
Output: GeeksForGeeks Using DOT notationIn 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; Example: The code below demonstrates how we can use the DOT notation to access enum values in typescript.
Output: "GeeksforGeeks" Using Object LookupAnother 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]; Example: In this example we are following above explained approach.
Output: GeeksForGeeks Using Object.entries MethodThis approach leverages Syntax:for (let [key, value] of Object.entries(EnumName)) {
Example:Here’s how you can use
Output:SUCCESS: 200 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |