TypeScript Enumeration Type

TypeScript Enumeration Type

1. Overview

An enumeration type is a name given to a set of values.

enum type is common in C++ and Java . TypeScript also adds enum type based on the original JavaScript type.

For example, if we need to define a set of roles and need to use numbers to represent them, we can use the following code to locate them:

enum role{
    STUDENT,
    TEACHER,
    ADMIN
}


In the above code, we define role as an enumeration type, which contains three values. TypeScript will automatically assign serial numbers to each value, starting from 0 by default, and their values ​​are 0 1 2.

Of course, we can also customize each value. If not all are defined, the subsequent values ​​will be incremented according to the previous values.

The sample code is as follows:

enum role1 {
    student = 1,
    // The next two values ​​are 2 and 3 respectively
    teacher,
    admin,
}
enum role2 {
    // Each name has a specified value student = 1,
    teacher = 3,
    admin = 6,
}

2. Digital Enumeration

The example we introduced above is a numeric enumeration type, but there is another point to note that if a field uses a constant or calculated value, we must set the initial value immediately following the field, otherwise an exception will be thrown.

The sample code is as follows:

;(function () {
  // Define a function const getValue: () => number = (): number => {
    return 0
  }

  enum role1 {
    student = getValue(),
    // teacher, // error Enumeration members must have an initializer expression.
    // admin, // error Enumeration members must have an initializer expression.
  }
  const TEACHER_ROLE: number = 3
  // Each name has a specified value enum role2 {
    student,
    teacher = TEACHER_ROLE,
    // admin, // error Enumeration members must have an initializer expression.
  }
})()

2.1 Reverse Mapping

The so-called reverse mapping is that you can access value through key , and access the key through the value.

We can get each specific value through .name or ['name'], or we can get the name corresponding to each value through [value].

The sample code is as follows:

enum role {
    student,
    teacher,
    admin,
}
console.log(role.admin) // 2
console.log(role['teacher']) //1
console.log(role[0]) //'student'

In fact, the enumeration type in TypeScript is an object after being compiled into JavaScript code. Let's compile the enumeration type above.

The compiled code is as follows:

"use strict";
var role;
(function (role) {
    role[role["student"] = 0] = "student";
    role[role["teacher"] = 1] = "teacher";
    role[role["admin"] = 2] = "admin";
})(role || (role = {}));


This may be easier to understand. In fact, it is to assign values ​​to the role object through a self-adjusting function. After the assignment, it is as follows:

var role = {
    "student": 0,
    "teacher": 1,
    "admin" : 2, 
    0: "student", 
    1: "teacher", 
    2: "admin", 
} 


It is worth noting that reverse mapping is only supported in numeric enumerations, not in string enumerations added in version 2.4.

3. String Enumeration

The so-called string enumeration means that the value of each field in the enumeration must be a string, or other fields in the enumeration.

The sample code is as follows:

enum Person {
  name = 'A bowl of Zhou',
  hobby = 'coding',
  // Set the field in the enumeration as the value myName = name,
}
console.log(Person.name, Person.myName) // One bowl for one week

4. const enumeration

After we define a normal enumeration, a corresponding object will be created after it is compiled into JavaScript code. If enumeration is used, it increases the readability of the program and the compiled object is not required. const enumerations were added in TypeScript1.4 .

The const enumeration is translated into a fully embedded enumeration. The so-called fully embedded enumeration means that there is no corresponding object after compilation. It just gets the corresponding value from the enumeration and then replaces it. To define const enumeration, just add the const keyword in front of the normal enumeration.

The sample code is as follows:

const enum role {
    student,
    teacher,
    admin,
}
let admin = role.admin

The above code will be compiled as follows:

let admin = 2 /* admin */;


5. Summary

This article introduces two basic enumeration types: numeric enumeration and string enumeration. Array enumeration also has a concept of reflection mapping, which means that you can access the value through the key and the key through value . Finally, we also introduced const enumeration, which means that the so-called enumeration object is not generated after compilation.

This is the end of this article about TypeScript enumeration types. For more related TypeScript enumeration content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example code using Typescript in Vue
  • Do you understand functions and classes in TypeScript?
  • Do you understand interfaces and generics in TypeScript?
  • Introduction to TypeScript basic types
  • Learn about TypeScript data types in one article
  • Detailed explanation of how to use TypeScript type annotations

<<:  Implementation of MySQL scheduled database backup (full database backup)

>>:  Let IE6, IE7, IE8 support CSS3 rounded corners and shadow styles

Recommend

Detailed explanation of the transition attribute of simple CSS animation

1. Understanding of transition attributes 1. The ...

A brief discussion on three methods of asynchronous replication in MySQL 8.0

In this experiment, we configure MySQL standard a...

Implementation of MySQL scheduled backup script under Windows

On a Windows server, if you want to back up datab...

JS implementation of carousel carousel case

This article example shares the specific code of ...

How to view the type of mounted file system in Linux

Preface As you know, Linux supports many file sys...

How to install Postgres 12 + pgadmin in local Docker (support Apple M1)

Table of contents introduce Support Intel CPU Sup...

Web Design: When the Title Cannot Be Displayed Completely

<br />I just saw the newly revamped ChinaUI....

How to enable MySQL remote connection

For security reasons, MySql-Server only allows th...

How to write transparent CSS for images using filters

How to write transparent CSS for images using filt...

Introduction to Linux environment variables and process address space

Table of contents Linux environment variables and...

How to install iso file in Linux system

How to install iso files under Linux system? Inst...

Solution for importing more data from MySQL into Hive

Original derivative command: bin/sqoop import -co...