如何在TypeScript中比较枚举 [英] How to compare Enums in TypeScript

查看:380
本文介绍了如何在TypeScript中比较枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript中,我想比较两个包含枚举值的变量。这是我的最小代码示例:

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

使用 tsc 编译时(v 2.0。 3)我收到以下错误:

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


TS2365:运算符'==='不能应用于类型'E.A'和'E.B' 。

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

== !== !=
我尝试添加 const 关键字,但这似乎没有效果。
TypeScript规范表示以下:

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< ;,> ;,< =,> =,==,!=,===以及!==运算符

这些运算符要求将一种或两种操作数类型分配给另一种。结果始终是布尔基元类型。

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?

旁注

我在Atom编辑器中使用 atom-typescript ,我在编辑器中没有收到任何错误/警告。但是,当我在同一目录中运行 tsc 时,我得到了上面的错误。我以为他们应该使用相同的 tsconfig.json 文件,但显然并非如此。

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.

推荐答案

还有另一种方式:如果您不想以任何方式影响生成的javascript代码,则可以使用类型转换:

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');
}

奇怪的是,如果 id 函数被声明为返回与其参数完全相同的类型:

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; }

这篇关于如何在TypeScript中比较枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆