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

enum E {
  A,
  B
}

let e1: E = E.A
let e2: E = E.B

if (e1 === e2) {
  console.log("equal")
}

使用tsc(v2.0.3)编译时,我遇到以下错误:

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

==!==!=也一样.

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

这些运算符要求一种或两种操作数类型可分配给另一种.结果总是布尔基元类型.

这(我认为)解释了这个错误.但我怎样才能摆脱它呢?

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代码受到任何影响,可以使用类型转换:

let e1: E = E.A
let e2: E = E.B


if (e1 as E === e2 as E) {
  console.log("equal")
}

通常,这是由基于控制流的类型推断引起的.在当前的typescript实现中,每当涉及函数调用时,它都会关闭,因此您也可以这样做:

let id = a => a

let e1: E = id(E.A)
let e2: E = id(E.B)

if (e1 === e2) {
  console.log('equal');
}

奇怪的是,如果id函数被声明为返回与其agment完全相同的类型,那么仍然没有错误:

function id<T>(t: T): T { return t; }

Typescript相关问答推荐

物料UI图表仅在悬停后加载行

错误:note_modules/@types/note/globals.d.ts:72:13 -错误TS 2403:后续变量声明必须具有相同的类型

如何将单元测试中的私有订阅变量设置为空(或未定义)?

如何根据数据类型动态注入组件?

即使子网是公共的,AWS CDK EventBridge ECS任务也无法分配公共IP地址

node—redis:如何在redis timeSeries上查询argmin?

在配置对象上映射时,类型脚本不正确地推断函数参数

为什么TypeScript失go 了类型推断,默认为any?''

TypeScrip:逐个 case Select 退出noUncheck kedIndexedAccess

如何解决类型T不能用于索引类型{ A:typeof A; B:typeof B;. }'

如何消除在Next.js中使用Reaction上下文的延迟?

在数据加载后,如何使用NgFor在使用异步管道的可观测对象上生成子组件?

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

Angular:ngx-echart 5.2.2与Angular 9集成错误:NG 8002:无法绑定到选项,因为它不是div的已知属性'

有没有办法取消分发元组的联合?

基于泛型的类型脚本修改类型

两个名称不同的相同打字界面-如何使其干燥/避免重复?

类型';只读<;部分<;字符串|记录<;字符串、字符串|未定义&>';上不存在TS 2339错误属性.属性&q;x&q;不存在字符串

换行TypeScript';s具有泛型类型的推断数据类型

覆盖高阶组件中的 prop 时的泛型推理