Explanation of TypeScript enumeration types
- 2021-12-04 09:07:21
- OfStack
Foreword:
TypeScript
The enumeration type is added on the basis of the original type of ES, so that the
TypeScript
You can also give a group of numeric names, which is friendly to developers. You can understand that enumeration is a dictionary.
Enumeration types are defined using enum:
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
Day of the enumeration type defined above, which has 7 values,
TypeScript
Each value is assigned a number, starting from 0 by default. When using it, you can use names without remembering the correspondence between numbers and names:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
The following is the effect after translating the above code into JavaScript:
var Day = void 0;
(function (Day) {
Day[Day["SUNDAY"] = 0] = "SUNDAY";
Day[Day["MONDAY"] = 1] = "MONDAY";
Day[Day["TUESDAY"] = 2] = "TUESDAY";
Day[Day["WEDNESDAY"] = 3] = "WEDNESDAY";
Day[Day["THURSDAY"] = 4] = "THURSDAY";
Day[Day["FRIDAY"] = 5] = "FRIDAY";
Day[Day["SATURDAY"] = 6] = "SATURDAY";
})(Day || (Day = {}));
As you can see, every 1 value is assigned a corresponding number.
In TypeScript, we need to get the members of the enumerated collection in the form of points:
console.log(Day.SUNDAY) // 0
console.log(Day.MONDAY) // 1
Having finished the basic use of enumeration types, let's look at the common enumeration types under 1.
1. Numeric enumeration
In the above example, when only the constant name is specified, a set of numbers incrementing from 0 by default is defined, which is called number enumeration. If you want to increment from another value, you can specify the index value of the first value:
enum Color {
Red = 2,
Blue,
Yellow
}
console.log(Color.Red, Color.Blue, Color.Yellow); // 2 3 4
You can specify 1 index value for 1 field, and those that do not specify an index value after them will be added by 1 in turn:
// Specify some fields, and use the default incremental index for others
enum Status {
Ok = 200,
Created,
Accepted,
BadRequest = 400,
Unauthorized
}
console.log(Status.Created, Status.Accepted, Status.Unauthorized); // 201 202 401
In addition, you can assign discontinuous arbitrary index values to each field:
enum Status {
Success = 200,
NotFound = 404,
Error = 500
}
console.log(Status.Success, Status.NotFound, Status.Error); // 200 404 500
Numeric enumerations can use calculated values and constants when defining values. Note, however, that if a field uses a calculated value or constant, then the field immediately following the field must have an initial value, and the default incremental value cannot be used here. Let's look at the example:
// The initial value is the calculated value
const getValue = () => {
return 0;
};
enum ErrorIndex {
a = getValue(),
b, // error Enumeration members must have initialized values
c
}
enum RightIndex {
a = getValue(),
b = 1,
c
}
// The initial value is constant
const Start = 1;
enum Index {
a = Start,
b, // error Enumeration members must have initialized values
c
}
2. String enumeration
TypeScript
An enumeration that defines a string literal is called a string enumeration, and the string enumeration value requires that the value of each field must be a string literal or another string enumeration member in the enumeration value:
// Use string literals
enum Message {
Error = "Sorry, error",
Success = "Hoho, success"
}
console.log(Message.Error); // 'Sorry, error'
// Use other enumeration members in enumeration values
enum Message {
Error = "error message",
ServerError = Error,
ClientError = Error
}
console.log(Message.Error); // 'error message'
console.log(Message.ServerError); // 'error message'
Note: Other enumeration members here refer to enumeration members in the same enumeration value. Because string enumeration cannot use constants or calculated values, members in other enumeration values cannot be used.
3. Reverse mapping
When defining the value of an enumerated type, you can use the
Enum['key']
Or
Enum.key
Gets the corresponding value in the form of
value
.
TypeScript
Reverse mapping is also supported, but reverse mapping only supports numeric enumeration, not string enumeration.
Look at the following example:
enum Status {
Success = 200,
NotFound = 404,
Error = 500
}
console.log(Status["Success"]); // 200
console.log(Status[200]); // 'Success'
console.log(Status[Status["Success"]]); // 'Success'
TypeScript
The enumeration defined in is actually an object after compilation. In the generated code, the enumeration type is compiled into an object, which contains a forward mapping (name-
>
value) and reverse mapping (value-
>
name).
Let's take a look at the
Status
Compiled effect:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
0
As you can see,
TypeScript
The field name of the defined enumeration value is taken as the attribute name and attribute value of the object respectively, and the field value of the enumeration value is taken as the attribute value and attribute name of the object respectively, and added to the object at the same time. In this way, you can get the value by enumerating the field name of the value, and you can also get the field name by enumerating the value of the value.
4. Heterogeneous enumeration
Heterogeneous enumeration means that the member values in the enumeration values have both numeric and string types, as follows:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
1
Asynchronous enumeration is not recommended during development. Because when a class 1 value is often sorted into an enumeration value, their characteristics are similar. For example, when making an interface request, the return status code is a numerical value if it is a prompt information, it is a string, so when using enumeration, it is often possible to avoid using heterogeneous enumeration, mainly sorting out the types.
5. Constant enumeration
In
TypeScript
After the enumeration value is defined, compile into
JavaScript
The code of creates a corresponding object, which can be used when the program is running. But what if you use enumerations just to make your program readable and don't need compiled objects? This will increase the amount of compiled code by 1.
TypeScript
1 in
const enum
(Constant enumeration), preceded by the statement defining the enumeration
const
Keyword, so the compiled code will not create this object, but will only get the corresponding value from the enumeration and replace it:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
2
After the above code is compiled into JavaScript, it looks like this:
var Status;
(function(Status) {
Status[(Status["Off"] = 0)] = "Off";
Status[(Status["On"] = 1)] = "On";
})(Status || (Status = {}));
var status = Status.On;
var animal = 0; // Dog
For
Status
First, define a variable Status, and then define an immediate execution function, which is given in the function
Status
To add the corresponding attribute, first
Status[“Off”] = 0
It's for
Status
Object sets the Off property and the value is set to 0. The return value of this assignment expression is the value to the right of the equal sign, that is, 0, so Status [Status
[“Off”] = 0] = "Off"
Equivalent to
Status[0] = “Off”
. After creating this object, assign the On attribute value of Status to status; Let's look at the processing of animal again. The compiled code does not create an Animal object like Status, but directly puts
Animal.Dog
The value of 0 is replaced by the value of 0
const animal = Animal.Dog
The Animal. Dog position of the expression.
By defining constant enumerations, you can maintain an associated set of constants in a clear, structured manner. And because the definition is erased after translation, inline member values are no worse in code size and performance than inline constant values directly.
6. Enumeration member types and union enumeration types
If all members in the enumeration value are literal values, then each member of the enumeration and the enumeration value itself can be used as a type. We call such enumeration members literal enumeration members.
The values of enumeration members that meet the conditions are as follows:
Enumeration members without initial values, such as:enum E { A }
The value is a literal string, for example:
enum E { A = 'a' }
Values are numeric literals, or numeric literals with the-sign, such as:
enum E { A = 1 }、enum E { A = -1 }
(1) Enumerate member types
When all enumeration members have literal enumeration values, enumeration members become types:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
4
As you can see, line 7 of the code uses the
Animal.Dog
As a type, specify the interface
Dog
Must have 1 type field of type
Animal.Dog
.
(2) Joint enumeration types
When the enumeration value meets the criteria, the enumeration value can be regarded as a union type containing all members:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
5
The above example defines the interface
TypeScript
0
Adj.
TypeScript
1
The type of the field is enumerated value
Status
, then at this time
TypeScript
1
The property value of must be
Status.Off
And one of Status. On, which is equivalent to
status: Status.Off | Status.On
.
7. Enumeration merge
After talking about common enumeration types, let's finally look at the concept of enumeration merging. For values of enumerated types, we can declare them separately:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
6
At this time
TypeScript
This enumeration value is merged and compiled into
JavaScript
The code of is as follows:
enum Day {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6
}
7