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

Background gradient animation effect made by css3

Achieve results Implementation Code html <h1 c...

Analysis of the project process in idea packaging and uploading to cloud service

one. First of all, you have to package it in idea...

How to install MySQL 8.0.13 in Alibaba Cloud CentOS 7

1. Download the MySQL installation package (there...

A detailed introduction to the CSS naming specification BEM from QQtabBar

BEM from QQtabBar First of all, what does BEM mea...

How to implement Echats chart large screen adaptation

Table of contents describe accomplish The project...

Making a simple game engine with React Native

Table of contents Introduction Get started A brie...

CocosCreator Getting Started Tutorial: Making Your First Game with TS

Table of contents premise TypeScript vs JavaScrip...

Function overloading in TypeScript

Table of contents 1. Function signature 2. Functi...

Let's talk about the problem of Vue integrating sweetalert2 prompt component

Table of contents 1. Project Integration 1. CDN i...

W3C Tutorial (6): W3C CSS Activities

A style sheet describes how a document should be ...

Div exceeds hidden text and hides the CSS code beyond the div part

Before hiding: After hiding: CSS: Copy code The co...

MySQL 8.0.15 compressed version installation graphic tutorial

This article shares the installation method of My...

Analysis of the principle of Nginx using Lua module to implement WAF

Table of contents 1. Background of WAF 2. What is...

Vue uses WebSocket to simulate the chat function

The effect shows that two browsers simulate each ...