为什么这个代码不能在打字稿中编译?
问题描述:
为什么在下面的例子中不能编译这段代码?为什么这个代码不能在打字稿中编译?
“|| 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'
。
现在,打字稿足够聪明,可以在输入第二个条件块时自动输入this.greeting
作为'test'
。
显然,'test' != 'test2'
永远不会是假的,它可能是一个错误,以检查该条件,因为你的整个if
语句将总是返回true。
你可能想写:
if (this.greeting != "test" && this.greeting != "test2") {
答
通过你已经达到了|| this.greeting != "test2"
部分时,编译器知道了肯定this.greeting
必须是"test"
,因此缩小了this.greeting
的类型字面类型"test"
,无法与"test2"
进行比较。
看起来像解释器中的错误,我将操作符更改为'&&',错误消失了,无论是生成JavaScript的方式。 –
这是很好的打字稿捡起来并标记错误,但有一点更多的思想“操作员不能应用”的错误的两个文字类型与一个共同的基础可以被更有意义的消息沿线“条件是永远是真的“(或”永远不会是真的)“,这将减少导致这个问题的那种混乱。 – Duncan