In application development, it is often involved to use a number to represent a certain state. For example, in the following example, numbers are used to represent the publication status of an article: 0: ‘draft’, 1: ‘not published’, 2: ‘published’. In other words, this state property has only three values: 0, 1, 2. If you use 0, 1, and 2 literals in code to represent states, you might get confused over time about which state the number corresponds to, and you might get some other numbers mixed in over time. In this case, using enumerated types is most appropriate, because enumerated types have two characteristics:

  • Give each set of numbers a more understandable name

  • There are only a few fixed values in an enumeration, and there is no possibility of going out of range

    const post = { title: ‘Hello TS’, content: ‘TS is a typed superset of JS’, status: 0 }

Enumerations are a very common data structure in many traditional programming languages. However, there is no such data structure in JS, and most of the time enumeration is simulated using an object.

const postStatus = { Draft: 0, Unpublished: 1, Published: 2, } enum PostStatus { Draft = 0, Unpublished = 1, Published = 2, } const post = { title: '... ', content: '... ', status: PostStatus.Draft }Copy the code

Enumeration types invade runtime code and affect compiled results. Most types used in TS are eventually removed after compilation because they are left and right to provide type checking during development. The enumeration is not deleted; it is compiled into a two-way key-value pair object. In a two-way key-value pair, you can either get a value by a key or you can get a key by a value. The purpose is to dynamically obtain enumeration names based on enumeration values, that is, to access the corresponding enumeration names in code by means of indexers. Constant enumerations are recommended if you can be sure your code doesn’t use indexers to access enumerations.

Var PostStatus; (function(PostStatus){ PostStatus[PostStatus['Daft'] = 0] = 'Draft'; PostStatus[PostStatus['Unpublished'] = 1] = 'Unpublished'; PostStatus[PostStatus['Published'] = 2] = 'Published' })(PostStatus||(PostStatus = {})) console.log(PostStatus) // { // 0: 'Draft', // 1: 'Unpublished', // 2: 'Published', // Draft: 0, // Unpublished: 1, // Published: 2, // }Copy the code

The use of constant enumerations is to precede the enum keyword with const.

Enum PostStatus {Draft = 0, Unpublished = 1, Published = 2,} const post = {title: '... ', content: '... ', status: poststatus. Draft} var post = {... status: 0 }Copy the code