Enumerations are data types that are supported by TypeScript. Enumerations allow you to define a set of named constants. Use them to more easily document intent or create a different set of cases. Mostly used in object-oriented programming languages such as Java and C#, enumerations are now 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 and use cases, the various enumeration types and the next steps in learning them.

What is an enumeration in TypeScript?

Many programming languages (such as C, C#, and Java) have enum data types, while JavaScript does not. But TypeScript does, and TypeScript has both number-based and string-based enumerations. typeScript enumerations allow developers to define a set of named constants. Using them makes it easier to document intent or create a different set of cases.

The syntax of an enumeration is as follows.

1
2
3
4
5
6
7
8
enum States {
    Apple,
    Orange
    Banana
    Watermelon
}
// 使用
var fruit = States.Watermelon;

What to look for when using enumerations in TypeScript

Firstly the values in the enumeration are constants, i.e. the enumeration is type safe and will return a compilation error when reassigning values. Secondly enumerations should be finite, which helps the user to create a custom constant system. An enumeration is an object when it is compiled: it creates a memory-efficient custom constant in JavaScript that is flexible enough to express a documented intent for use as a judgmental use case.

1
2
3
4
enum requestStatus {
    success = 200
    error = 400
}
1
2
3
4
5
6
7
8
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 }

Types of common enumerations

Numeric enumerations and String enumerations are the most common types of enumerations we use in TypeScript, and I’ll introduce you to their features and how to use them with examples.

**Numeric enumerations

Numeric enumerations store numeric values as strings. Let’s define them using the enum keyword. I’ll show the numeric enumeration in TypeScript with an example that stores a set of different types of cars.

1
2
3
4
5
6
enum CarType {
    Honda,
    Toyota,
    Subaru,
    Hyundai
}

The enumeration value CarType has four values: Honda, Toyota, Subaru and Hyundai. The enumerated values start at 0 and increment by 1 for each member, as follows.

Honda = 0

Toyota = 1

Subaru = 2

Hyundai = 3

You can initialize the first value yourself if needed, as follows.

1
2
3
4
5
6
enum CarType {
    Honda = 1,
    Toyota,
    Subaru,
    Hyundai
}

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

You may wonder, if I change the last value, will the previous values be decremented according to the last defined value? Let’s try.

1
2
3
4
5
6
enum CarType {
    Honda,
    Toyota,
    Subaru,
    Hyundai = 100
}

Unfortunately this does not work and the current example has the following values

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

Note: It is not necessary to assign sequential values to enumeration members. You can assign any desired value to it

String enumerations

String enumerations are similar to numeric enumerations, but their enumeration values are initialized using string values instead of numeric values. String enumerations have better readability than numeric enumerations, making it easier to debug programs.

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

1
2
3
4
5
6
7
8
9
enum CarType {
    Honda = "HONDA",
    Toyota = "TOYOTA",
    Subaru = "SUBARU",
    Hyundai = "HYUNDAI"
}

// 访问字符串枚举
CarType.Toyota; //return TOYOTA

Note: String enumeration values need to be initialized separately.

Enumeration reverse mapping

An enumeration can retrieve the num value using its corresponding enumeration member value. Using the reverse mapping, the member value and the name of the member value can be accessed, see the following example.

1
2
3
4
5
6
7
8
9
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 the reverse mapping. Let us look at another example.

1
2
3
4
5
6
7
enum CarType {
    Honda = 1,
    Toyota,
    Subaru,
    Hyundai
}
console.log(CarType)

The following output will be seen in the browser’s console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{ 
    '1':'Honda',
    '2':'Toyota',
    '3':'Subaru',
    '4':'Hyundai',
    Honda:1,
    Toyota:2,
    Subaru:3,
    Hyundai:4 
}

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

Computational Enumeration

The value of an enumeration member can be a constant value or a calculated value. See the following example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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 the enumeration contains both computed and constant members, the uninitialized enumeration member will appear first and may also come after other initialized members with numeric constants. The next example will show the error.

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

You can declare the above enumeration like this.

1
2
3
4
5
6

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

That’s all this article is about, by explaining what is enumeration and what we should pay attention to when using enumeration. To our common enumeration types (numeric enumeration, string enumeration), enumeration reverse mapping, computational enumeration. I believe you have a certain understanding of the enumeration, if there is anything that is not clear or what is wrong with the article welcome to correct, thank you.