Basic definition

  • Enumerations belong to types
enum Sex {
  Man, // Separated by commas
  Women
}
Copy the code

Digital enumeration

  • Numeric enumeration, according to the initialization value, set the property value increment
  • This parameter is optional. The default value is 0
enum Status{
  success = 0, 
  fail
}
console.log(Status[0], Status.success)
Copy the code

The enumeration of characters

  • Character enumerations do not increment, so you need to set a value for each property
enum Status{
  success = 'success'
  fail = 'fail'
}
Copy the code

Constant member

  • The first member has no initializer
enum E { X } // x does not have an initializer
Copy the code
  • It has no initializer and the enumerator before it is a numeric constant
enum E { A = 1, B }  // B has no initializer and the previous enumerator is a number
Copy the code

Constant enumeration expression

An expression that satisfies one of the following conditions and whose enumerated value is a constant member

  • An enumerated expression literal (mainly a string literal or a number literal)
  • A reference to a previously defined constant enumerator (which can be defined in a different enumeration type)
  • A bracketed constant enumeration expression
  • One of the unary operators +, -, ~ applies to constant enumeration expressions
  • Constant enumeration expression as a binary operator, +, -, *, /, %, < <, > >, > > >, &, |, ^ operation object. If the constant enumeration expression evaluates to NaN or Infinity, an error is reported at compile time.

Enumerator type

  • A constant enumerator with no initial value
  • Any string literal (e.g. “foo”, “bar”, “baz”)
  • Any numeric literal (e.g., 1, 100)
  • Numeric literals with unary – symbols applied (e.g. -1, -100)
enum ShapeKind {
    Circle,
    Square,
}
// Use enumerators as type definitions
interface Circle {
    kind: ShapeKind.Circle;
    radius: number;
}


interface Square {
    kind: ShapeKind.Square;
    sideLength: number;
}


let c: Circle = {
    kind: ShapeKind.Square,
    // ~~~~~~~~~~~~~~~~ Error!
    radius: 100,}Copy the code

Const enumeration

const enum Enum {
    A = 1,
    B = A * 2
}
Copy the code

External enumeration

An external enumeration is used to describe the shape of an existing enumeration type

declare enum Enum {
    A = 1,
    B,
    C = 2
}
Copy the code