为什么这部分不能在以下示例中编译?
" || 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
}
}
}
答案 0 :(得分:6)
这实际上是一个有效的错误,并且阻止你犯错。
if (this.greeting != "test" || this.greeting != "test2") {
由于您使用||
,第二个条件将不会被执行,除非this.greeting == 'test'
。
现在,typescript足够智能,当它进入第二个条件块时自动键入this.greeting
为'test'
。
显然,'test' != 'test2'
永远不会是错误的,检查该条件可能是错误的,因为您的整个if
语句将始终返回true。
你可能想写:
if (this.greeting != "test" && this.greeting != "test2") {
答案 1 :(得分:1)
当您到达|| this.greeting != "test2"
部分时,编译器肯定知道this.greeting
必须为"test"
,因此它会缩小类型this.greeting
到文字类型"test"
,无法与"test2"
进行比较。