Questions
What are enums and how do you use them in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new feature that needs to represent a set of related constants, such as the different roles that a user can have.
You could use a set of const variables, but this would not be a very elegant solution.
The Challenge
Explain what enums are in TypeScript and how you would use them to solve this problem. What are the key benefits of using enums?
A junior engineer might not be aware of enums. They might try to solve this problem by using a set of `const` variables, which would be a less elegant and less type-safe solution.
A senior engineer would know that enums are the perfect tool for this job. They would be able to explain what enums are and how to use them to create a set of named constants.
Step 1: Understand What Enums Are
An enum is a way to define a set of named constants.
Step 2: The Different Types of Enums
| Type | Description |
|---|---|
| Numeric | The default type of enum. The first member is initialized to 0, and each subsequent member is incremented by 1. |
| String | Each member must be initialized with a string value. |
| Heterogeneous | A mix of numeric and string members. |
Step 3: Use an Enum
Here’s how we can use an enum to represent the different roles that a user can have:
enum Role {
Admin,
Editor,
Viewer
}
const myRole: Role = Role.Admin;The Benefits of Using Enums
| Benefit | Description |
|---|---|
| Readability | Enums make your code more readable by giving names to a set of related constants. |
| Type Safety | Enums provide compile-time type safety, which can help you to catch errors early. |
Practice Question
You have a numeric enum and you want to get the name of a member from its value. How would you do this?