为什么这一段在下面的例子中编译不通过?
"|| this.greeting != "test2"
"
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
setGreeting(g) {
this.greeting = g;
}
test() {
if(this.greeting != "test" || this.greeting != "test2"){
//this.greeting cound still be test3
}
}
}
最佳答案
这实际上是一个有效的错误,可以防止您犯错。
if (this.greeting != "test" || this.greeting != "test2") {
因为您使用的是 ||
,所以第二个条件不会被执行,除非 this.greeting == 'test'
。< br/>
现在,typescript 足够聪明,可以在进入第二个条件 block 时自动将 this.greeting
键入为 'test'
。
很明显,'test' != 'test2'
永远不会为假,检查该条件可能是错误的,因为您的整个 if
语句将 < em>总是返回真。
你可能想写:
if (this.greeting != "test" && this.greeting != "test2") {
关于typescript - 为什么这段代码不能用 typescript 编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179995/