为什么这个部分不能在以下示例中编译?
“ || 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 } } }链接到示例
Why does this piece not compile in the following example?
"|| 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 } } }Link to example
最满意答案
这实际上是一个有效的错误,并防止你犯错误。
if (this.greeting != "test" || this.greeting != "test2") {因为你正在使用|| ,除非this.greeting == 'test'否则不会执行第二个条件。 现在,打字稿足够智能,可以在进入第二个条件块时自动输入this.greeting作为'test' 。
显然, 'test' != 'test2'永远不会是假的,检查那个条件可能是错误的,因为你的整个if语句总是会返回true。
你可能想写:
if (this.greeting != "test" && this.greeting != "test2") {It's actually a valid error, and prevented you from making a mistake.
if (this.greeting != "test" || this.greeting != "test2") {Since you're using ||, the second condition will not be executed unless this.greeting == 'test'. Now, typescript is smart enough to automatically type this.greeting as 'test' when it enters the second conditional block.
Clearly, 'test' != 'test2' will never be false, and it's probably a mistake to check for that condition, since your entire if statement will always return true.
You probably wanted to write:
if (this.greeting != "test" && this.greeting != "test2") {更多推荐
发布评论