How to compare Enums in TypeScript

后端 未结 9 2270
攒了一身酷
攒了一身酷 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';
    

提交回复
热议问题