This is the fifth day of my participation in Gwen Challenge
The enumeration
Using enumerations we can define constants with names. Use enumerations to clearly express intent or to create a differentiated set of use cases. TypeScript supports numeric and string-based enumerations.
Digital enumeration
First let’s look at numeric enumerations, which you’ll be familiar with if you’ve used other programming languages.
enum Direction {
Up = 1,
Down,
Left,
Right
}
Copy the code
As above, we define a numeric enumeration with Up initialized to 1. The rest of the members will automatically grow from 1. In other words, direction. Up is 1, Down is 2, Left is 3, and Right is 4.
We can also dispense with initializers altogether:
enum Direction {
Up,
Down,
Left,
Right,
}
Copy the code
Now, the Up value is 0, the Down value is 1 and so on. This self-growing behavior is useful when we don’t care about the value of the member, but be aware that the value of each enumerator is different.
Using enumerations is simple: access enumeration members by enumeration properties and access enumeration types by enumeration names:
enum Response {
No = 0,
Yes = 1,}function respond(recipient: string, message: Response) :void {
// ...
}
respond("Princess Caroline", Response.Yes)
Copy the code
The enumeration value of the first position is not a constant, and the values of the following positions need to be specified
enum E {
A = getSomeValue(),
B, // error! 'A' is not constant-initialized, so 'B' needs an initializer
}
Copy the code
String enumeration
The concept of string enumerations is simple, but has subtle runtime differences. In a string enumeration, each member must be initialized with either a string literal or another string enumeration member.
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",}Copy the code
Because string enumerations have no self-growing behavior, string enumerations can be serialized well. String enumerations allow you to provide a value that is meaningful and readable at runtime, independent of the enumerator’s name.
Heterogeneous enumeration
Technically, enumerations can mix string and numeric members, but we generally don’t do this:
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",}Copy the code
Computed and constant members
Each enumerator takes a value, which can be constant or computed. Enumerators are treated as constants if:
It is the first member of the enumeration and has no initializer, in which case it is given the value 0:
// E.X is constant:
enum E { X }
Copy the code
It has no initializer and the enumerator before it is a numeric constant. In this case, the value of the current enumerator is incremented by the value of its previous enumerator.
// All enum members in 'E1' and 'E2' are constant.
enum E1 { X, Y, Z }
enum E2 {
A = 1, B, C
}
Copy the code