条件在打字稿中重叠
假设我有一些这样的简单逻辑:
let bool = false
const seven = 7
const arr = [1,2,3,4,5,6,7]
arr.forEach(element => {
if (element === seven) {
bool = true
}
});
如果“ bool”设置为true,现在我不打算呼叫函数:
if (bool === true){
doSomething()
}
在这种情况下,Typescript给出了错误:
This condition will always return 'false' since the types 'false' and 'true' have no overlap.
Typescript抱怨即使从逻辑上讲,我知道Bool将由触发条件块的时间。我该如何解决?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道Typescript编译器会在这样的事情上抱怨,但是这再次是具有这样一种条件语句的一种奇怪的方式,因为:
但是
,您可以:
if(bool){...}
(强烈推荐)if(((bool as as boolean)==== true){...}
(它有效,但请不要这样)I did not know that the Typescript compiler would complain on something like this, but again it's a strange way to have such a condition statement since:
is the same as:
But yeah you can either:
if (bool) { ... }
(highly recommended)if((bool as boolean) === true ) { ... }
(it works but please don't do this)