为什么这段代码不能用打字稿编译?(Why does this code not compile in typescript?)

编程入门 行业动态 更新时间:2024-10-28 14:32:42
为什么这段代码不能用打字稿编译?(Why does this code not compile in 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 } } }

链接到示例

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

更多推荐

本文发布于:2023-04-27 14:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这段   不能用   代码   typescript   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!