How to compare Enums in TypeScript

后端 未结 9 2264
攒了一身酷
攒了一身酷 2021-02-06 20:14

In TypeScript, I want to compare two variables containing enum values. Here\'s my minimal code example:

enum E {
  A,
  B
}

let e1: E = E.A
let e2: E = E.B

if (         


        
相关标签:
9条回答
  • 2021-02-06 20:50

    In typescript an example enum:

    enum Example {
       type1,
       type2
    };
    

    is transformed to javascript into this object:

    Example {
        '0': 'type1', 'type1': 0,
        '1': 'type2', 'type2': 1
    }
    

    I had many problems with comparison enums in typescript. This simple script solves the problem:

    enum Example {
        type1 = 'type1',
        type2 = 'type2'
    };
    

    then in javascript, the object is transformed into:

    Example {
        'type1': 'type1',
        'type2': 'type2'
    }
    

    If you don't need to use enums - it's better not to use. Typescript has more advanced types, more here: https://www.typescriptlang.org/docs/handbook/advanced-types.html You can use instead:

    type Example = 'type1' | 'type2';
    
    0 讨论(0)
  • 2021-02-06 20:51

    I would define values for Enum like this and compare with ===

    const enum AnimalInfo {
    Tiger = "Tiger",
    Lion = "Lion"
    }
    
    let tigerStr = "Tiger";
    
    if (tigerStr === AnimalInfo.Tiger) {
      console.log('true');
    } else {
      console.log('false');
    }
    
    0 讨论(0)
  • 2021-02-06 20:56

    There is another way: if you don't want generated javascript code to be affected in any way, you can use type cast:

    let e1: E = E.A
    let e2: E = E.B
    
    
    if (e1 as E === e2 as E) {
      console.log("equal")
    }
    

    In general, this is caused by control-flow based type inference. With current typescript implementation, it's turned off whenever function call is involved, so you can also do this:

    let id = a => a
    
    let e1: E = id(E.A)
    let e2: E = id(E.B)
    
    if (e1 === e2) {
      console.log('equal');
    }
    

    The weird thing is, there is still no error if the id function is declared to return precisely the same type as its agument:

    function id<T>(t: T): T { return t; }
    
    0 讨论(0)
提交回复
热议问题