为什么这段代码不能用打字稿编译?

use*_*670 2 typescript

为什么这个部分不能在以下示例中编译?

" || 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)

链接到示例

Rob*_*Rob 7

这实际上是一个有效的错误,并防止你犯错误.

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)