Table of Contents
Enum
Basic usage
Home Web Front-end JS Tutorial Let's talk about the usage of Enum (enumeration) in TypeScript

Let's talk about the usage of Enum (enumeration) in TypeScript

Jul 05, 2021 am 10:19 AM
enum javascript typescript

This article will introduce you to the Enum (enumeration) syntax in TypeScript, talk about the basic usage of Enum, and how to use native JavaScript to implement Enum.

Let's talk about the usage of Enum (enumeration) in TypeScript

Enum

Enum is a new syntax in TypeScript, also called enumeration. It is generally used to manage multiple Constants of the same series (that is, variables that cannot be modified) are used for status judgment.

A common status judgment in the Web is to handle different response status codes accordingly when processing requests:

const handleResponseStatus = (status: number): void => {
  switch (status) {
    case 200: // 请求成功时
      // Do something...
      break;
    case 400: // 请求失败时
      // Do something...
      break;
    default:
      throw (new Error('No have status code!'));
  }
};
Copy after login

But because the response status codes are all pre-defined , so there is no controversy. It is normal for the code to be written like this. However, if the backend customizes some codes when an error occurs on the server and tells the frontend what errors these codes represent, then the above function may become like this:

const handleWrongStatus = (status: string): void => {
  switch (status) {
    case 'A':
      // Do something...
      break;
    case 'B':
      // Do something...
      break;
    case 'C':
      // Do something...
      break;
    default:
      throw (new Error('No have wrong code!'));
  }
};
Copy after login

If it’s this kind of code, let alone someone who just took over it, even if you wrote it two weeks ago, you probably won’t be able to remember what they represent without looking through the document.

But if you make good use of Enum, you can avoid the above situation.

Basic usage

Let’s first look at how to define Enum. It is very similar to Object in usage:

enum requestStatusCodes {
  error,
  success,
}
Copy after login

There is no need to add an equal sign between the content and the name. Directly describe the variables in the Enum within the curly brackets. It is more appropriate to call them constants rather than variables. Because the values ​​in the Enum cannot be modified, there is no need to worry about these defined rules being executed in the code. Changes occurred during the process, resulting in execution errors.

And since Enum is used to define the same series of constants, these constants should be able to maintain specific values. That's right, every constant in Enum can specify a specific value through =.

But if it is like the previous requestStatusCodes, there will be no error if no specific value is specified for error or success, because TypeScript will start from 0 starts to automatically increment the defined value, so the signed requestStatusCodes will have the same result as the following:

enum requestStatusCodes {
  error = 0,
  success = 1,
}console.log(requestStatusCodes.error) // 0
console.log(requestStatusCodes.success) // 1
Copy after login

In addition to numbers, it can also be defined as a string:

enum requestWrongCodes {
  missingParameter = 'A',
  wrongParameter = 'B',
  invalidToken = 'C',
}console.log(requestWrongCodes.wrongParameter) // 'B'
Copy after login

Of course you can also set different types in one enum, but this makes no sense at all:

enum requestStatusCodes {
  error = 0,
  success = 'OK',
}
Copy after login

After understanding how to define the basic Enum, then rewrite the ## in the previous code #handleResponseStatus and handleWrongStatus to make them semantically clearer.

First use Enum to define the status descriptions of the two:

enum requestStatusCodes {
  error = 400,
  success = 200,
}

enum requestWrongCodes {
  missingParameter = 'A',
  wrongParameterType = 'B',
  invalidToken = 'C',
}
Copy after login

Then modify the Switch judgment in

handleResponseStatus and handleWrongStatus:

const handleResponseStatus = (status: number): void => {
  switch (status) {
    case requestStatusCodes.success:
      // Do something...
      break;
    case requestStatusCodes.error:
      // Do something...
      break;
    default:
      throw (new Error('No have status code!'));
  }
};

const handleWrongStatus = (status: string): void => {
  // 如果觉得 requestWrongCodes.missingParameter 太长了,也可以用以下方式:
  const { missingParameter, wrongParameterType, invalidToken, } = requestWrongCodes;
  switch (status) {
    case missingParameter:
      // Do something...
      break;
    case wrongParameterType:
      // Do something...
      break;
    case invalidToken:
      // Do something...
      break;
    default:
      throw (new Error('No have wrong code!'));
  }
};
Copy after login

The modified code becomes much more intuitive, because the status codes are all put into Enum for unified management, so they can be represented by constant names. No matter how long it takes, you can clearly know what to do here. There is no need to even write comments or documentation, because code is the best documentation.

Make good use of Enum to make your code absolutely indispensable, but don’t be discouraged even if you don’t use TypeScript, because TypeScript will eventually be converted to JavaScript, so let’s take a look at how to implement Enum directly in JavaScript!

Use native JavaScript to implement Enum

As mentioned before, Enum is very similar to Object. If you study the code after Enum is compiled into javascript, you will find that it is really Object.

After Enum is compiled, it will become an object corresponding to Key and Value. This seems very simple. For convenience of use, let’s write its compilation method as a function:

const newEnum = (descriptions) => {
  const result = {};
  Object.keys(descriptions).forEach((description) => {
    result[result[description] = descriptions[description]] = description;
  });
  return result;
};

const responseStatus = newEnum({
  error: 400,
  success: 200,
});

// { '200': 'success', '400': 'error', error: 400, success: 200 }
console.log(responseStatus);
Copy after login

Although The result obtained is the same, but the most valuable

constant feature of Enum is lost. If it cannot be made unmodifiable, it may be inadvertently changed in the code, resulting in possible errors in the execution result. So you can use Object.freeze() at the end so that external operations cannot add, delete or redefine any Property:

const newEnum = (descriptions) => {
  const result = {};
  Object.keys(descriptions).forEach((description) => {
    result[result[description] = descriptions[description]] = description;
  });
  return Object.freeze(result);
};

const responseStatus = newEnum({
  error: 400,
  success: 200,
});

// 即使不小心修改了
responseStatus['200'] = 'aaaaaaaa';

// 仍然是 { '200': 'success', '400': 'error', error: 400, success: 200 }
console.log(responseStatus);
Copy after login

This way you can simply implement Enum in JavaScript.

Usage of const Enum

You can see from the previous JavaScript code that after compilation, Enum will become an Object with Key and Value corresponding to each other, that is to say, you can use Key or Value. Get the corresponding value,

But if you declare Enum with const, Object will not be generated after compilation.

Looking directly at the example, suppose I regenerate

responseState with const, and also use the Enum to make judgments with handleResponseStatus:

enum responseStatus {
  error = 400,
  success = 200,
}

const handleResponseStatus = (status: number): void => {
  switch (status) {
    case responseStatus.success:
      console.log('请求成功!');
      break;
    case responseStatus.error:
      console.log('请求失败!');
      break;
    default:
      throw (new Error('No have status code!'));
  }
};
Copy after login

Everything seems to be normal, but in the compiled JavaScript, you will find that Enum does not generate Object, but directly uses

const to declare the value in Enum.

There are several advantages to using

const to declare Enum:

  • If there are a lot of Enums to be used, the execution will not stop. Using IIFE to generate Object and binding Key and Value to Object will cause some efficiency losses and increase memory, but

    const will not generate Object, so there will be no above problems.

  • 就算到的 Enum 不多,判断时也需要一直从 Object 中找出对应的值,而如果是用 const 声明 Enum ,在编译成 JS 时就将声明的值直接放入判断中。

不过这样也就没法从 Enum 中反向取值了,因为它并不会产生对象:

const enum responseStatus {
  error = 400,
  success = 200,
}// 会出错,因为已经没有对象可供查找了
console.log(responseStatus[400])// 但这个不会有问题,因为编译的时候会直接填值
console.log(responseStatus.error)// 编译后:
// console.log(400)
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let's talk about the usage of Enum (enumeration) in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles