“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
preface
In fact, we mentioned enumerations earlier when we talked about the types of TS.
If you don’t understand the concept, you can think of enumerations simply as enumerations
The previous example used enum
enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH;
Copy the code
The advantage of enumerations is that we can define constants with names, and we can clearly express intent or create a differentiated set of use cases
TS supports numeric and string-based enumerations, starting with numeric enumerations
Digital enumeration
For example:
enum Direction {
Up = 1,
Down,
Left,
Right
}
Copy the code
This is an enumeration of numbers, and we initialize Up to 1, and the rest will automatically grow from 1.
Of course, there is no need to initialize, as follows:
enum Direction {
Up,
Down,
Left,
Right,
}
Copy the code
The default is to increment from 0
So how do you use enumerations?
The answer is that enumeration members are accessed by enumeration properties, and enumeration types are accessed by enumeration names. For example, when we talk about types:
enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH;
Copy the code
String enumeration
In a string enumeration, each member must be initialized with either a string literal or another string enumeration member. Such as:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",}Copy the code
String enumerations serialize well because string enumerations have no self-growing behavior. If you are debugging and have to read the runtime value of a numeric enumeration, the value is usually hard to read and does not express useful information, whereas string enumerations allow you to provide a run-time value that is meaningful and readable, independent of the enumerator’s name
You may be wondering if strings and numbers can be mixed. Note that enumerations do mix string and number members, but this is generally not recommended!
END
That’s all for this article. If you have any questions, please point out