How to compare Enums in TypeScript

2020-06-06 07:57发布

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 (e1 === e2) {
  console.log("equal")
}

When compiling with tsc (v 2.0.3) I get the following error:

TS2365: Operator '===' cannot be applied to types 'E.A' and 'E.B'.

Same with ==, !== and !=. I tried adding the const keyword but that seems to have no effect. The TypeScript spec says the following:

4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators

These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type.

Which (I think) explains the error. But how can I get round it?

Side note
I'm using the Atom editor with atom-typescript, and I don't get any errors/warnings in my editor. But when I run tsc in the same directory I get the error above. I thought they were supposed to use the same tsconfig.json file, but apparently that's not the case.

8条回答
Fickle 薄情
2楼-- · 2020-06-06 08:16

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,...}

查看更多
等我变得足够好
3楼-- · 2020-06-06 08:16

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';
查看更多
Ridiculous、
4楼-- · 2020-06-06 08:24

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; }
查看更多
smile是对你的礼貌
5楼-- · 2020-06-06 08:25

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").

查看更多
时光不老,我们不散
6楼-- · 2020-06-06 08:35

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.

查看更多
狗以群分
7楼-- · 2020-06-06 08:38

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');
}
查看更多
登录 后发表回答