How to compare Enums in TypeScript

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

    If was able to compare two enums with this

     if (product.ProductType && 
           (product.ProductType.toString() == ProductTypes[ProductTypes.Merchandises])) {
          // yes this item is of merchandises
      } 
    

    with ProductTypes being this export enum ProductTypes{Merchandises,Goods,...}

    0 讨论(0)
  • 2021-02-06 20:38

    In my case none of the above solutions worked, the reason was that i was casting the enum value to the enum object.

    After that i was trying to know if the enum was equivalent to another enum object... so i 've created the following generic functions:

      public static enumEquals<T>(e: any, e1: T, e2: T): boolean {
        const v1 = this.enumValue(e, e1);
        return v1 === this.enumValue(e, e2, typeof v1);
      }
    
      private static enumValue<T>(enumType: any, value: T, validType?: string) {
        let v = enumType[value];
        if (!validType) {
          return v;
        }
        while (typeof v !== validType) {
          v = enumType[v];
        }
        return v;
      }
    

    This is an example of my test case:

    enum SomeEnum {
      VALUE1, VALUE2, VALUE3, VALUE_DEF
    }
    
    const enumRefKey = localStorage.getItem('someKey');
    const parsedEnum = SomeEnum[enumRefKey] || SomeEnum.VALUE_DEF;
    console.log(parsedEnum);
    if (parsedEnum === SomeEnum.VALUE_DEF) {
      // do stuff
    }
    

    Obviously that code didn't worked, after i've tried the solutions given here at this questions i've found that when enumRefKey is valid console.log(parsedEnum) was printing numbers and the text VALUE_DEF when is not. The same result happend using all other solutions:

    • parsedEnum as SomeEnum
    • parsedEnum.valueOf()
    • SomeEnum[parsedEnum]

    The solution using the generic methods looks like this:

    enum SomeEnum {
      VALUE1, VALUE2, VALUE3, VALUE_DEF
    }
    
    const enumRefKey = localStorage.getItem('someKey');
    const parsedEnum = SomeEnum[enumRefKey] || SomeEnum.VALUE_DEF;
    console.log(parsedEnum);
    if (this.enumEquals(SomeEnum, parsedEnum, SomeEnum.VALUE_DEF) {
      // do stuff
    }
    

    I hope this helps somebody.

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2021-02-06 20:44

    The only thing that worked for me (in typescript 2.2.1) was this:

    if (E[e1] === E[e2]) {
      console.log("equal")
    }
    

    This compares the strings representing the names (eg. "A" and "B").

    0 讨论(0)
  • 2021-02-06 20:45

    Type casting enums to strings is a very valuable technique.

    For example;

    if (String(e1) === String(e2)) {
        console.log("equal, now actually works!")
    }
    
    0 讨论(0)
  • 2021-02-06 20:47

    Well I think I found something that works:

    if (e1.valueOf() === e2.valueOf()) {
      console.log("equal")
    }
    

    But I'm a bit surprised that this isn't mentioned anywhere in the documentation.

    0 讨论(0)
提交回复
热议问题