【发布时间】:2018-02-06 00:43:14
【问题描述】:
看看下面的code:
export class Smth {
private flag: boolean;
public update() {
this.flag = true;
this.inner();
if (this.flag === false) { // Operator '===' cannot be applied to types 'true' and 'false'.
console.log(123);
}
}
private inner() {
this.flag = false;
}
}
我不明白这行有什么问题
if (this.flag === false)
打字稿说
运算符 '===' 不能应用于类型 'true' 和 'false'。
但实际上有boolean和false。
我使用的是 typescript 2.6.2,但在线游乐场显示的结果与 2.7 相同。
这不是Operator '==' cannot be applied to types x and y in Typescript 2 的重复,因为该问题是关于比较常量的。但在我的代码中,它是一个可更改的类字段,并且有一个函数可以更改值。而且,它被称为。
this.flag = true;
this.inner(); // exectues this.flag = false;
if (this.flag === false) { // ... types 'true' and 'false'. - WHY?
【问题讨论】:
-
你为什么不写
if (!this.flag) { ... }? -
Operator '==' cannot be applied to types x and y in Typescript 2 的可能重复项(TL;DR:编译器可以看到您正在尝试将永远正确的事物与永远错误的事物进行比较)
-
@jonrsharpe,因为在实际代码中我有 3 个值的枚举。
-
然后显示那个。请注意您发布的错误消息会导致许多现有资源,例如github.com/Microsoft/TypeScript/issues/11178
-
@JoeClay,不,这并不总是
true。我打电话给this.inner(),它会将this.flag的状态更改为false。标志不再是true。
标签: typescript