May 07, 2021 TypeScript
Using enumerals, we can define some numeric constants with names.
Enumerants
enum
the enum keyword.
enum Direction {
Up = 1,
Down,
Left,
Right
}
An enumerity type can contain zero or more enumerumered members. An enumeration member has a numeric value, which can be a constant or a calculated value When the following conditions are met, the enumeration member is treated as a constant:
0
+
,
-
,
~
The ion operator is applied to the constant enumeration expression
+
,
-
,
*
,
/
,
%
,
<<
,
>>
,
>>>
,
&
,
|
,
^
Binary operator, constant enumeration expression as one of its operational objects If the constant enumeration
NaN
Infinity
an error is reported during the compilation phase.
Enumeration members in all other cases are treated as values that need to be calculated.
enum FileAccess {
// constant members
None,
Read = 1 << 1,
Write = 1 << 2,
ReadWrite = Read | Write
// computed member
G = "123".length
}
Enumerity is an object that really exists at runtime. One reason is that this allows reverse mapping from enumeration values to enumeration names.
enum Enum {
A
}
let a = Enum.A;
let nameOfA = Enum[Enum.A]; // "A"
Compiled into:
var Enum;
(function (Enum) {
Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));
var a = Enum.A;
var nameOfA = Enum[Enum.A]; // "A"
In the generated code, the enumerate type is compiled into an object that contains a two-way map
name
-gt;
value
and
value
-gt;
name
R
eference enumeration members always generate property access once and are never inline. I
n most cases this is a good and correct solution. S
ometimes, however, the demand is more stringent. W
hen accessing enumeration values, you can use constant enumeration to avoid generating extra code and indirect references.
Constant enumerants
enum
modifier before the
const
keyword.
const enum Enum {
A = 1,
B = A * 2
}
Constant enumerations can only use constant enumeration expressions and, unlike regular enumerations, are removed during the compilation phase. C onstant enumeraled members are inline where they are used. This is because constant enumeration cannot have calculated members.
const enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]
The generated code is:
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];
External enumerity is used to describe the shape of an enumerity type that already exists.
declare enum Enum {
A = 1,
B,
C = 2
}
There is an important difference between external enumeration and non-external enumeration, in normal enumeration, members without initialization methods are treated as constant members. For a very large number of external enumerations, there is no initialization method that needs to be calculated.