TS: Extension of Enumeration

TS: Extension of Enumeration

1. Enumeration calculation

  • Enumeration members can be initialized using constant enumeration expressions :

    enum E {
          
          
        None ,
        OK = 1 << 1,
        Read = 1 << 2,
        Write = 2 << 1,
        ReadWrite = Read | Write,
        Pending = "123".length
    }
    

2. Enumeration member type

  • After enumeration members are enumerated, they have a special semantics;

  • Enumeration members become types:

    enum E {
          
           A , B }
    interface A {
          
          
        type : E.A;
        value : number
    }
    
    let c : A {
          
          
        type : E.B,	//error , A接口的type属性的类型为E.A
        value : 1
    }
    
  • Enumerations are objects that really exist at runtime:

    enum E {
          
           X , Y}
    function foo(obj : {
          
          X : number}){
          
          
        return obj,X;
    }
    
    foo(E);		//ok,E是一个真实存在的对象,X他的一个属性,值为0。
    

4. Reverse mapping of enumeration

  • In addition to the enumeration value obtained from the enumeration name, the enumeration can also obtain the enumeration name from the enumeration value.

    enum E {
          
          X , Y}
    console.log(E[0])	// "X"
    

5. Constant Enumeration

  • In order to avoid the overhead of additional generated code and additional indirect access to enumeration members, constenumeration can be used .

    const enum E{
          
          
        A = 1,
        B = 2 * A
    }
    
  • Constant enumeration can only use constant enumeration expressions;

  • Constant enumeration will be deleted during the compilation phase and replaced by the value of the enumeration;

  • External enumeration: External enumeration is used to describe the shape of an existing enumeration type.

    • There is an important difference between external enumeration and non-external enumeration: In normal enumeration, members without initialization methods are treated as constant members.
    • For non-constant external enumerations, when there is no initialization method, it is considered to be calculated.
    declare enum E{
          
          
        A = 1,
        B , 
        C = 3
    }
    

Guess you like

Origin blog.csdn.net/yivisir/article/details/109560532