如何比较 TypeScript 中的枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39785320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare Enums in TypeScript
提问by John J. Camilleri
In TypeScript, I want to compare two variables containing enum values. Here's my minimal code example:
在 TypeScript 中,我想比较两个包含枚举值的变量。这是我的最小代码示例:
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:
使用tsc
(v 2.0.3)编译时,出现以下错误:
TS2365: Operator '===' cannot be applied to types 'E.A' and 'E.B'.
TS2365:运算符“===”不能应用于“EA”和“E.B”类型。
Same with ==
, !==
and !=
.
I tried adding the const
keyword but that seems to have no effect.
The TypeScript specsays the following:
与==
,!==
和相同!=
。我尝试添加const
关键字,但似乎没有效果。该打字稿规范说的情况如下:
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.
4.19.3 <、>、<=、>=、==、!=、=== 和 !== 运算符
这些运算符要求一种或两种操作数类型可分配给另一个。结果总是布尔基元类型。
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.
旁注
我正在使用带有atom-typescript的 Atom 编辑器,我的编辑器中没有任何错误/警告。但是当我tsc
在同一个目录中运行时,我得到了上面的错误。我以为他们应该使用相同的tsconfig.json
文件,但显然情况并非如此。
采纳答案by artem
There is another way: if you don't want generated javascript code to be affected in any way, you can use type cast:
还有另一种方法:如果您不希望以任何方式影响生成的 javascript 代码,您可以使用类型转换:
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:
奇怪的是,如果id
函数被声明为返回与其参数完全相同的类型,仍然没有错误:
function id<T>(t: T): T { return t; }
回答by John J. Camilleri
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.
但令我感到有些惊讶的是,文档中的任何地方都没有提到这一点。
回答by Bellash
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,...}
ProductTypes 是这个 export enum ProductTypes{Merchandises,Goods,...}
回答by sendon1982
I would define values for Enum like this and compare with ===
我会像这样定义 Enum 的值并与 ===
const enum AnimalInfo {
Tiger = "Tiger",
Lion = "Lion"
}
let tigerStr = "Tiger";
if (tigerStr === AnimalInfo.Tiger) {
console.log('true');
} else {
console.log('false');
}
回答by Russ
The only thing that worked for me (in typescript 2.2.1) was this:
唯一对我有用(在打字稿 2.2.1 中)是这样的:
if (E[e1] === E[e2]) {
console.log("equal")
}
This compares the strings representing the names (eg. "A" and "B").
这将比较表示名称的字符串(例如“A”和“B”)。
回答by W92
In typescript an example enum:
在打字稿一个示例枚举:
enum Example {
type1,
type2
};
is transformed to javascript into this object:
被转换为 javascript 到这个对象:
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:
然后在 javascript 中,对象被转换为:
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.htmlYou can use instead:
如果您不需要使用枚举 - 最好不要使用。Typescript 有更高级的类型,更多在这里:https://www.typescriptlang.org/docs/handbook/advanced-types.html 你可以改用:
type Example = 'type1' | 'type2';
回答by Luis Limas
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 genericfunctions:
在那之后,我试图知道枚举是否等同于另一个枚举对象......所以我创建了以下通用函数:
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:
显然,该代码不起作用,在我尝试了此处给出的解决方案后,我发现当 enumRefKey 有效时,console.log(parsedEnum)正在打印数字,而文本 VALUE_DEF 则不是。使用所有其他解决方案发生了相同的结果:
- parsedEnum as SomeEnum
- parsedEnum.valueOf()
- SomeEnum[parsedEnum]
- parsedEnum 为 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.
我希望这对某人有帮助。
回答by seBaka28
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)
也不会编译,因为e1
在这种情况下是0
(因为 A 是第一个枚举“选项”),因此false
这意味着永远不会达到第二个状态(不管第二个语句在这种情况下是否有效)