为什么这个部分不能在以下示例中编译?
" || 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
这实际上是一个有效的错误,并防止你犯错误.
if (this.greeting != "test" || this.greeting != "test2") {
Run Code Online (Sandbox Code Playgroud)
由于您正在使用||,第二个条件将不会被执行,除非this.greeting == 'test'.
现在,打字稿足够智能以自动键入this.greeting如'test'当它进入第二条件块.
显然,'test' != 'test2'永远不会是假的,检查那个条件可能是错误的,因为你的整个if陈述总是会返回true.
你可能想写:
if (this.greeting != "test" && this.greeting != "test2") {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |