How to compare Enums in TypeScript

后端 未结 9 2265
攒了一身酷
攒了一身酷 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:40

    The error is thrown because the compiler realizes that the statement is always false and therefore redundant. You declare two variables which are clearly not equal and then try and see whether they are equal.

    If you change it to e.g.:

    enum E {
      A,
      B
    }
    
    foo() {
      let e1: E = E.A
      let e2: E
      e2 = foo();
    
      if (e1 === e2) {
        console.log("equal")
      }
    }
    
    bar(): E {
      return E.B
    }
    

    it should compile without an error.

    On a sidenote, sth. like

    let e1 = E.A;
    if (e1 && e1 === E.B) {
      ...
    }
    

    would also not compile, as e1 in this case is 0 (as A is the first enum 'option') and therefore false which means that the second state would never be reached (disregarding whether the second statement would even be valid in this case)

提交回复
热议问题