JavaScript > TypeScript > TypeScript Basics > Enums
TypeScript String Enum Example
This snippet illustrates the use of string enums in TypeScript. Unlike numeric enums, string enums explicitly assign string values to each member. This enhances readability and debugging capabilities, making them suitable for scenarios where the string representation of the enum value is important.
Defining a String Enum
This code defines a string enum called `Direction`. Each member is explicitly assigned a string value. The `move` variable is assigned the value `Direction.Up`, which will output "UP" when printed to the console.
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
let move: Direction = Direction.Up;
console.log(move); // Output: UP
Concepts Behind String Enums
String enums provide a more readable alternative to numeric enums by associating each enum member with a specific string value. This can be particularly useful when you need to log enum values or when you're interacting with external systems that expect string representations.
Real-Life Use Case
Consider a system that handles user roles. Using a string enum to represent roles allows for easy debugging and logging, as the role names are directly visible in the output.
Real-Life Use Case Code Example
This example demonstrates how a string enum `UserRole` can be used for authorization purposes. The `authorize` function checks if a given user role is `Admin` and returns a boolean value accordingly.
enum UserRole {
Admin = "ADMIN",
Editor = "EDITOR",
Viewer = "VIEWER"
}
function authorize(role: UserRole): boolean {
if (role === UserRole.Admin) {
return true;
} else {
return false;
}
}
console.log(authorize(UserRole.Editor)); // Output: false
Best Practices
Interview Tip
Be prepared to discuss the trade-offs between numeric and string enums. Explain that string enums offer better readability and debuggability but may consume more memory. Also, be ready to provide examples of when string enums are particularly useful.
When to Use Them
String enums are particularly useful in scenarios where:
Memory Footprint
String enums typically have a larger memory footprint compared to numeric enums because they store string values. The memory usage depends on the length of the strings used for each enum member.
Alternatives
Alternatives to string enums include:
Pros
Cons
FAQ
-
Are string enums type-safe?
Yes, TypeScript enforces type safety for string enums, ensuring that only valid enum values are used. -
Can I mix numeric and string values in a string enum?
No, string enums must have string values assigned to all of their members. -
When should I choose a string enum over a numeric enum?
Choose a string enum when readability, debuggability, and integration with external systems that expect string values are important considerations.