问题答案 12026年5月29日 06:31
How to create enum type in TypeScript?
Creating enum types in TypeScript primarily involves two approaches: numeric enums and string enums. Enums are a special type that allow defining a named collection for a set of related values. Below, I will detail both approaches with some examples.Numeric EnumsNumeric enums are the most common type of enums in TypeScript. In numeric enums, the values of members default to incrementing from 0; however, you can manually specify the value for any member.Example:In this example, the value of is explicitly set to 1, while subsequent enum members (, , ) increment automatically. Thus, has a value of 2, has a value of 3, and so on.String EnumsString enums require each member to be initialized with a string literal or another string enum member.Example:In this example, each member of the enum is explicitly set to a specific string. This enhances code readability and maintainability while avoiding the use of magic strings.SummaryUsing enums can improve code readability and robustness. Implementing enums in TypeScript is very intuitive, and both numeric and string enums have their appropriate use cases. Typically, when defining a set of fixed constants, enums are an excellent choice. For example, when handling data such as directions or status messages that form fixed sets, enums provide a convenient way to organize these values.