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

查看:39
本文介绍了如何比较 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-typescript 的 Atom 编辑器,我没有收到任何错误/我的编辑器中的警告.但是当我在同一目录中运行 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")
}

一般来说,这是由基于控制流的类型推断引起的.使用当前的 typescript 实现,只要涉及函数调用,它就会关闭,因此您也可以这样做:

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 函数被声明为返回与其 agument 完全相同的类型,仍然没有错误:

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天全站免登陆