[英]Typescript compile error on enum equality check
I created this typescript file to show the problem:我创建了这个 typescript 文件来显示问题:
enum E {
one,
two
}
console.log(E.one)
console.log(E.two)
let n: E = E.one
if (n === E.one) console.log("equal");
if (n === E.two) console.log("equal");
I get compile error from tsc on second if:如果出现以下情况,我会在第二次从 tsc 收到编译错误:
test.ts:11:5 - error TS2367: This condition will always return 'false' since the types 'E.one' and 'E.two' have no overlap.
I can't find out why it is happening.我不知道为什么会这样。 Am I doing something wrong?
难道我做错了什么?
This is intended behaviour (see this issue ).这是预期的行为(请参阅此问题)。
TypeScript's control flow analysis is smart enough to see that you just assigned E.one
to n
. TypeScript 的控制流分析足够聪明,可以看到您刚刚将
E.one
分配给了n
。 There is now "invisible" type information associated with n
which narrows down its type to E.one
and will lead to the error in the if-statement because it knows that the condition will always evaluate to false
.现在有与
n
关联的“不可见”类型信息,它将其类型缩小到E.one
并将导致 if 语句中的错误,因为它知道条件将始终评估为false
。
If you want to avoid this behaviour, you can use the as
operator which lets TypeScript conveniently forget the narrowed type information about n
.如果你想避免这种行为,你可以使用
as
运算符,它可以让 TypeScript 方便地忘记关于n
的缩小类型信息。
let n: E = E.one as E
if (n === E.one) console.log("equal");
if (n === E.two) console.log("equal");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.