TypeScript enumeration basics and examples

TypeScript enumeration basics and examples

Preface

Enumerations are a data type supported by TypeScript. Enumerations allow you to define a set of named constants. Use them to more easily document intent or create a set of different cases. Enums are mostly used in object-oriented programming languages ​​like Java and C#, and now they are also available in TypeScript. They are one of the few features of TypeScript that is not a type-level extension of JavaScript. Next I will demonstrate the basics of TypeScript enumerations along with use cases, various enumeration types and next steps for learning.

What are enums in TypeScript?

Many programming languages, such as C, C#, and Java, have enum data types, but JavaScript does not. But TypeScript can, TypeScript has both numeric-based and string-based enums. TypeScript enums allow developers to define a set of named constants. Use them to more easily document intent or create a set of different cases.

The syntax of an enumeration is as follows:

enum States {
    Apple,
    Orange,
    Banana,
    Watermelon
}
// Usage var fruit = States.Watermelon;

What to pay attention to when using enumerations in TypeScript

First, the values ​​in the enumeration are constants, that is, the enumeration is type-safe and a compilation error will be returned when the value is reassigned. Second, enumerations should be finite, which helps users create a custom constant system. Enumeration is an object after being compiled: create memory-efficient custom constants in JavaScript, flexible and easy to express record intentions and convenient as judgment use cases.

enum requestStatus {
    success = 200
    error = 400
}

let requestStatus;
(function (requestStatus) {
    requestStatus[requestStatus["success"] = 200] = "success"
    requestStatus[requestStatus["error"] = 400] = "error"
})(requestStatus || (requestStatus = {}));

// requestStatus:
// { '200': 'success', '400': 'error', error: 400, success: 200 }

Common enumeration types

Numeric enumeration and string enumeration are the most commonly used enumeration types in TypeScript. Below I will use examples to introduce their characteristics and how to use them.

** Numeric enumeration

Numeric enumerations store numeric values ​​as strings. Let's define them using the enum keyword. Below I'll demonstrate numeric enumerations in TypeScript using an example that stores a set of different types of cars:

enum CarType {
    Honda,
    Toyota,
    Subaru,
    Hyundai
}

The CarType enumeration has four values: Honda, Toyota, Subaru, and Hyundai. The enumeration value starts at 0 and the value of each member increases by 1, as shown below:

Honda = 0

Toyota = 1

Subaru = 2

Hyundai = 3

If necessary you can initialize the first value yourself, like this:

enum CarType {
    Honda = 1,
    Toyota,
    Subaru,
    Hyundai
}

In the example above, Honda initializes the first member with the value 1. The remaining numbers will be incremented by one.

You might be thinking, if I change the last value, will the previous values ​​be decremented by the last defined value? Let's try it:

enum CarType {
    Honda,
    Toyota,
    Subaru,
    Hyundai = 100
}

Unfortunately this does not work, the values ​​in the current example are:

enum CarType {
    Honda, // 1
    Toyota, // 2
    Subaru, // 3
    Hyundai // 100
}

Note: It is not necessary to assign ordinal values ​​to enumeration members. You can assign it any value you want

String Enumeration

String enumerations are similar to numeric enumerations, but their enumeration values ​​are initialized with string values ​​instead of numeric values. String enumerations are more readable than numeric enumerations, making it easier to debug your program.

The following example uses the same information as the numeric enumeration example, but expressed as a string enumeration:

enum CarType {
    Honda = "HONDA",
    Toyota = "TOYOTA",
    Subaru = "SUBARU",
    Hyundai = "HYUNDAI"
}

// Access string enumeration CarType.Toyota; //return TOYOTA

Note: String enumeration values ​​need to be initialized individually.

Enumeration reverse mapping

Enumerations can retrieve the num value using its corresponding enumeration member value. Using reverse mapping, you can access member values ​​and their names, as shown in the following example:

enum CarType {
    Honda = 1,
    Toyota,
    Subaru,
    Hyundai
}
CarType.Subaru; //return 3
CarType.["Subaru"]; //return 3
CarType[3]; //return Subaru

CarType[3] returns its member name "Subaru" due to reverse mapping. Let's look at another example:

enum CarType {
    Honda = 1,
    Toyota,
    Subaru,
    Hyundai
}
console.log(CarType)

You will see the following output in your browser's console:

{
'1': 'Honda',
'2': 'Toyota',
'3': 'Subaru',
'4': 'Hyundai',
Honda: 1,
Toyota: 2,
Subaru: 3,
Hyundai: 4
}

Each value of an enumeration appears twice in the internally stored enumeration object.

Calculated Enumeration

The values ​​of enumeration members can be constant values ​​or computed values. Take a look at the following example:

enum CarType {
    Honda = 1,
    Toyota = getCarTypeCode('toyota'),
    Subaru = Toyota * 3,
    Hyundai = 10
}

function getCarTypeCode(carName: string): number {
    if (carName === 'toyota') {
        return 5;
    }
}

CarType.Toyota; // returns 5
CarType.Subaru; // returns 15

If an enumeration contains both computed and constant members, uninitialized enumeration members appear first, possibly after other initialized members with numeric constants. The next example will display an error:

enum CarType {
    Toyota = getCarTypeCode('toyota'),
    Honda, // Error: Enum member must have initializer
    Subaru,
    Hyundai = Toyota * 3,
}

You can declare the above enumeration like this:

enum CarType {
    Honda,
    Hyundai,
    Toyota = getCarTypeCode('toyota'),
    Subaru = Toyota * 3

The above is the full content of this article. By explaining what enumeration is, we should pay attention to what we should pay attention to when using enumeration. To our commonly used enumeration types (numeric enumeration, string enumeration), enumeration reverse mapping, calculated enumeration. I believe you already have some understanding of enumeration

Summarize

This concludes this article on the basics and examples of TypeScript enumerations. For more information on TypeScript enumerations, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Introduction to TypeScript basic types
  • Share 13 basic syntax of Typescript
  • TypeScript Basics Tutorial: Triple Slash Instructions
  • Detailed explanation of TypeScript's basic types

<<:  Summary of commonly used multi-table modification statements in Mysql and Oracle

>>:  Markup Language - Title

Recommend

Implementation of HTML to PDF screenshot saving function

Using Technology itext.jar: Convert byte file inp...

Detailed steps for IDEA to integrate docker to achieve remote deployment

1. Enable remote access to the docker server Log ...

How to download excel stream files and set download file name in vue

Table of contents Overview 1. Download via URL 2....

Writing Snake Game with Native JS

This article shares the specific code of writing ...

Basic introductory tutorial on MySQL partition tables

Preface In a recent project, we need to save a la...

Use nginx + secondary domain name + https support

Step 1: Add a secondary domain name to the Alibab...

How to configure user role permissions in Jenkins

Jenkins configuration of user role permissions re...

How to implement multiple parameters in el-dropdown in ElementUI

Recently, due to the increase in buttons in the b...

How to create Apache image using Dockerfile

Table of contents 1. Docker Image 2. Create an in...

Sample code for partitioning and formatting a disk larger than 20TB on centos6

1. Server environment configuration: 1. Check dis...

MySQL method steps to determine whether it is a subset

Table of contents 1. Problem 2. Solution Option 1...

How to customize Docker images using Dockerfile

Customizing images using Dockerfile Image customi...

Docker installation and configuration command code examples

Docker installation Install dependency packages s...