- Mastering TypeScript 3
- Nathan Rozentals
- 459字
- 2021-07-02 12:42:43
Enums
Enums are a special type that has been borrowed from other languages such as C#, C++, and Java, and provides a solution to the problem of special numbers. An enum associates a human-readable name for a specific number. Consider the following code:
enum DoorState { Open, Closed, Ajar }
Here, we have defined an enum called DoorState to represent the state of a door. Valid values for this door state are Open, Closed, or Ajar. Under the hood (in the generated JavaScript), TypeScript will assign a numeric value to each of these human-readable enum values. In this example, the enum value DoorState.Open will equate to a numeric value of 0. Likewise, the enum value DoorState.Closed will equate to the numeric value of 1, and the enum value DoorState.Ajar will equate to 2. Let's take a quick look at how we would use these enum values:
var openDoor = DoorState.Open; console.log(`openDoor is: ${openDoor}`);
Here, the first line of this snippet creates a variable named openDoor, and sets its value to DoorState.Open. The second line simply logs the value of the openDoor variable to the console. The output of this would be as follows:
openDoor is: 0
This clearly shows that the TypeScript compiler has substituted the enum value of DoorState.Open with the numeric value 0.
Now, let's use this enum in a slightly different way:
var closedDoor = DoorState["Closed"]; console.log(`closedDoor is : ${closedDoor}`);
This code snippet uses a string value of "Closed" to look up the enum type, and assigns the resulting enum value to the closedDoor variable. The output of this code would be as follows:
closedDoor is : 1
This sample clearly shows that the enum value of DoorState.Closed is the same as the enum value of DoorState["Closed"], because both variants resolve to the numeric value of 1.
Enums are a handy way of defining an easily remembered, human-readable name to a special number. Using human-readable enums, instead of just scattering various special numbers around in our code, makes the intent of the code clearer. Using an application-wide value named DoorState.Open or DoorState.Closed is far simpler than remembering to set a value to 0 for Open, 1 for Closed, and 3 for Ajar. As well as making our code more readable, and more maintainable, using enums also protects our code base whenever these special numeric values change, because they are all defined in one place.
One last note on enums is that we can set the numeric value manually, if needs be, as follows:
enum DoorState { Open = 3, Closed = 7, Ajar = 10 }
Here, we have overridden the default values of the enum to set DoorState.Open to 3, DoorState.Closed to 7, and DoorState.Ajar to 10.