This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Using enumerations we can define constants with names. Use enumerations to clearly express intent or to create a differentiated set of use cases. TypeScript supports numeric and string-based enumerations.

Digital enumeration

For example, if we define a numeric enumeration, Up is initialized to 1, and the rest of the members grow automatically from 1.

enum Direction {
    Up = 1,
    Down,
    Left = 5,
    Right
}
let c: Direction = Direction.Up;
let d: Direction = Direction.Down;
let e: Direction = Direction.Left;
let f: Direction = Direction.Right;
console.log(c,d,e,f) / / 1 2 5 6
Copy the code

When the Up is not initialized, the Up value is 0, the Down value is 1, and so on.

String enumeration

In a string enumeration, each member must be initialized with either a string literal or another string enumeration member.

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}
Copy the code

String enumerations have no behavior of self-growth.

Use enumerated

We can access enumeration members by enumeration properties, and enumeration names by enumeration types:

enum MyEnum { No, Yes }
function respond(recipient: string, message: MyEnum) :void {
  // ...
}
respond("Princess Caroline", MyEnum.Yes)

enum Color {Red, Green, Blue}
let c: Color = Color.Red;
let d: Color = Color.Green;
let e: Color = Color.Blue;
console.log(c,d,e) / / 0
Copy the code

Members of the enumeration

Each enumerator takes a value, which can be constant or computed.

Enumerator members are initialized using constant enumeration expressions. An expression is a constant enumerated expression when it satisfies one of the following conditions:

  • 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
  • Unary operator+.-.~One of them applies to constant enumeration expressions
  • Constant enumeration expressions as binary operators+.-.*./.%.<<.>>.>>>.&.|.^Operation object of. If the constant enumeration expression is evaluatedNaNorInfinity, an error is reported at compile time.
enum FileAccess {
  // constant members
  None,
  Read = 1 << 1,
  Write = 1 << 2,
  ReadWrite = Read | Write,
  // computed member
  G = "123".length
}
Copy the code

When the value of an enumerator contains a string, expressions are not allowed to evaluate in subsequent enumerations:

enum Color {Red="hh", Green = Math.random(), Blue=4}
// error! Computed values are not permitted in an enum with string valued members.
let c: Color = Color.Red;
let d: Color = Color.Green;
let e: Color = Color.Blue;
console.log(c,d,e) // "hh", 0, 4
Copy the code

The type and joint enumeration of an enumerator

A literal enumerator is a constant enumerator that has no initial value, or whose value is initialized to

  • Any string literal (e.g."foo"."bar"."baz")
  • Any numeric literal (e.g.1.100)
  • Apply unary-The numeric literal of a symbol (e.g.- 1.- 100.)

When all enumerators have literal enumeration values, it takes on a special semantics.

First, enumerators become types!

enum ShapeKind {
  Circle,
  Square
}
interface Circle {
  kind: ShapeKind.Circle;
  radius: number;
}
interface Square {
  kind: ShapeKind.Square;
  sideLength: number;
}
let c: Circle = {
  kind: ShapeKind.Square, // Here, the enumerator shapekind. Square is the type
  // Error! Type 'ShapeKind.Square' is not assignable to type 'ShapeKind.Circle'.
  radius: 100,}Copy the code

Second, the enumeration type itself becomes a union of each enumeration member.

enum E {
  Foo,
  Bar,
}
function f(x: E) {
  if(x ! == E.Foo || x ! == E.Bar) {// Always true.
    / / ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
    // Error! This condition will always return 'true' since the types 'E.Foo' and 'E.Bar' have no overlap.}}Copy the code

Enumeration at runtime

Enumerations are objects that actually exist at run time. For example, the following enumeration:

enum E {
  X, Y, Z
}
function f(obj: { X: number }) {
  return obj.X;
}
f(E); // Works, since 'E' has a property named 'X' which is a number.
Copy the code

Reverse mapping

In addition to creating an object with attribute names as object members, numeric enumerators also have reverse mapping from enumeration values to enumeration names.

enum Enum {
  A
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

enum Color {Red, Green, Blue = 4}
let c: string = Color[0];
let d: string = Color[1];
let e: string = Color[2];
console.log(c,d,e) // "Red", "Green", undefined
Copy the code

constThe enumeration

An enumeration defined by const that, when compiled by the compiler, is an object that we can use at runtime.

const enum E {
  Foo,
  Bar,
}
let num1: E = E.Foo

enum F {
  Foo,
  Bar,
}
let num2: F = F.Foo
Copy the code

Compile result:

let num1 = 0 /* Foo */;

var F;
(function (F) {
    F[F["Foo"] = 0] = "Foo";
    F[F["Bar"] = 1] = "Bar";
})(F || (F = {}));
let num2 = F.Foo;
Copy the code

As you can see in the compiled code, const enumerations are replaced by 0 directly, which saves the overhead of generating code.

declareThe enumeration

External enumerations (Declare enumerations) are used to describe existing enumeration types.

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

There is an important difference between external and non-external enumerations. In normal enumerations, members that have no initialization methods are treated as constant members. External enumerations of nonconstant numbers are treated as computations when there is no initialization method.

External enumerations are similar to type assertions. The presence of this declaration means that the current object must exist in the context of the current development environment. The TS type system can detect all declare declared variables in the current entire file directory context, so you can use the current object at will.

reference

  • enums_cn
  • enums_en
  • How do the different enum variants work in TypeScript? – Stack Overflow