Understanding and application scenarios of enumeration types in TypeScript

Understanding and application scenarios of enumeration types in TypeScript

1. What is

An enumeration is a set of named integer constants. It is used to declare a set of named constants. When a variable has several possible values, it can be defined as an enumeration type.

In layman's terms, an enumeration is a set of all possible values ​​of an object.

It is also very common in daily life. For example, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, which represent the day of the week, can be regarded as an enumeration.

Enumerations are declared similarly to structures and unions, and have the form:

enum enumeration name{
Identifier ①[=integer constant],
Identifier②[=integer constant],
...
Identifier N[=integer constant],
}enumeration variable;

2. Use

Enumerations are defined using the enum keyword in the following format:

enum xxx { ... }

The way to declare a keyword as an enumeration type is as follows:

//Declare d as enumeration type Direction
let d : Direction;

Types can be divided into:

  • Numeric Enumeration
  • String Enumeration
  • Heterogeneous Enumerations

Numeric Enumeration

When we declare an enumeration type, although no values ​​are assigned to them, their values ​​are actually the default numeric type, and they are accumulated by default starting from 0:

enum Direction {
    Up, // The default value is 0
    Down, // default value is 1
    Left, // default value is 2
    Right // The default value is 3
}

console.log(Direction.Up === 0); // true
console.log(Direction.Down === 1); // true
console.log(Direction.Left === 2); // true
console.log(Direction.Right === 3); // true

If we assign the first value, the subsequent values ​​will also be accumulated by 1 according to the previous value:

enum Direction {
    Up = 10,
    Down,
    Left,
    Right
}

console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right); // 10 11 12 13

String Enumeration

The value of the enumeration type can actually be a string type:

enum Direction {
    Up = 'Up',
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}

console.log(Direction['Right'], Direction.Up); // Right Up

If a variable is set to a string, subsequent fields also need to be assigned strings, otherwise an error will be reported:

enum Direction {
 Up = 'UP',
 Down, // error TS1061: Enum member must have initializer
 Left, // error TS1061: Enum member must have initializer
 Right // error TS1061: Enum member must have initializer
}

Heterogeneous Enumerations

That is, combine digital enumeration and string enumeration and use them together, as follows:

enum BooleanLikeHeterogeneousEnum {
    No = 0,
    Yes = "YES",
}

Usually we rarely use heterogeneous enumerations

nature

Now an enumeration case is as follows:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

After compilation, the javascript is as follows:

var Direction;
(function (Direction) {
    Direction[Direction["Up"] = 0] = "Up";
    Direction[Direction["Down"] = 1] = "Down";
    Direction[Direction["Left"] = 2] = "Left";
    Direction[Direction["Right"] = 3] = "Right";
})(Direction || (Direction = {}));

As can be seen from the above code, Direction[Direction["Up"] = 0] = "Up" can be divided into

  • Direction["Up"] = 0
  • Direction[0] = "Up"

So after defining the enumeration type, you can get the corresponding value through forward and reverse mapping, as follows:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

console.log(Direction.Up === 0); // true
console.log(Direction[0]); // Up

And enumerations defined in multiple places can be merged, as follows:

enum Direction {
    Up = 'Up',
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}

enum Direction {
    Center = 1
}

After compilation, the js code is as follows:

var Direction;
(function (Direction) {
    Direction["Up"] = "Up";
    Direction["Down"] = "Down";
    Direction["Left"] = "Left";
    Direction["Right"] = "Right";
})(Direction || (Direction = {}));
(function (Direction) {
    Direction[Direction["Center"] = 1] = "Center";
})(Direction || (Direction = {}));

As you can see, the Direction object properties are superimposed.

3. Application Scenarios

Let's take a real-life example. The fields returned by the backend use 0 - 6 to mark the corresponding dates. At this time, enumeration can be used to improve code readability, as follows:

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

console.log(Days["Sun"] === 0); // true
console.log(Days["Mon"] === 1); // true
console.log(Days["Tue"] === 2); // true
console.log(Days["Sat"] === 6); // true

Including when the backend returns 0, 1, etc., we can define it through enumeration, which can improve the readability of the code and facilitate subsequent maintenance.

References

https://zh.wikipedia.org/wiki/%E6%9E%9A%E4%B8%BE

Summarize

This concludes this article on the understanding and application scenarios of enumeration types in TypeScript. For more relevant TypeScript enumeration type content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Explain TypeScript enumeration types in detail
  • TypeScript Enumeration Type

<<:  MySQL database introduction: detailed explanation of multi-instance configuration method

>>:  MySQL database introduction: detailed explanation of database backup operation

Recommend

Implementation of Nginx forwarding matching rules

1. Regular expression matching ~ for case-sensiti...

JavaScript pie chart example

Drawing EffectsImplementation Code JavaScript var...

Do you know how to use Vue to take screenshots of web pages?

Table of contents 1. Install html2Canvas 2. Intro...

Node.js+express+socket realizes online real-time multi-person chat room

This article shares the specific code of Node.js+...

MySQL uses events to complete scheduled tasks

Events can specify the execution of SQL code once...

MySQL pessimistic locking and optimistic locking implementation

Table of contents Preface Actual Combat 1. No loc...

How to encapsulate axios request with vue

In fact, it is very simple to encapsulate axios i...

Implementation of tomcat deployment project and integration with IDEA

Table of contents 3 ways to deploy projects with ...

JS implements request dispatcher

Table of contents Abstraction and reuse Serial Se...

html+css+js to realize the function of photo preview and upload picture

Preface: When we are making web pages, we often n...

Summary of 6 Linux log viewing methods

As a backend programmer, you deal with Linux in m...