One, numerical enumeration

(Used to name a set of constants. When a variable has multiple values, it can be listed as an enumerated type.)

Declare an enumeration type, numeric by default, assign the first value, then add:

enum Direction {
    Up,
    Down=10,
    Left,
    Right
}

console.log(Direction.Up === 0); // true
console.log(Direction.Down === 10); // true
console.log(Direction.Left === 11); // true
console.log(Direction.Right === 12); // trueCopy the code

String enumeration

enum Direction {
    Up = 'Up',
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}

console.log(Direction['Right'], Direction.Up); // Right UpCopy the code

3. Heterogeneous enumeration (mixed use)

enum BooleanLikeHeterogeneousEnum {
    No = 0,
    Yes = "YES",}Copy the code

Reverse mapping (enumeration)

enum Direction {
    Up,
    Down,
    Left,
    Right
}

console.log(Direction[0]); // UpCopy the code

Nature of enumeration

Think of an enumeration as an object

enum Direction {
    Up = 10,
    Down,
    Left,
    Right
}

console.log(Direction[10], Direction['Right']); // Up 13Copy the code

Direction[Direction[“Up”] = 10] = “Up” (Direction[10] = “Up”), so we can think of an enumerated type as a JavaScript object that, due to its construction, has the property of simultaneous forward and backward mapping.

Normally on the enumeration

Enumerations can be declared to be always on, which benefits from TypeScript’s ability to omit them to optimize performance. Such as:

const enum Direction {
    Up = "Up",
    Down = 'Down',
    Left = 'Left',
    Right = 'Right'
}

const a = Direction.Up;Copy the code

After compiling javascript, it is:

var a = "Up";Copy the code

TypeScript removes Direction at this point and uses the Direction value as a performance enhancement.

Enumerator type

When an enumerator has a literal enumeration, it has special semantics, that is, the enumerator becomes a type.

For example, a numeric type is declared:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

const a = 0

console.log(a === Direction.Up) // truCopy the code

We use the member as a value, which seems to be fine because the member value itself is 0, so let’s add a few more lines:

 type c = 0

declare letB: c b = 1 // Type 1 cannot be assigned to type 0. B = direction. Up // okCopy the code

As we can see, the above results show that the members of this enumeration can actually be used as types, which is how enumerators are used as types.

Joint enumerated type

enum Direction {
    Up,
    Down,
    Left,
    Right
}

declare letA: Direction enum Animal {Dog, Cat} a = direction. Up // okCopy the code

We can put a statement for Direction type, as we declare a type of joint Direction. | of the Up Direction. Down | Direction. The Left | Direction. Right, Only members of these four types are eligible.