条件在打字稿中重叠

发布于 2025-02-01 22:35:29 字数 505 浏览 3 评论 0 原文

假设我有一些这样的简单逻辑:

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将由触发条件块的时间。我该如何解决?

Lets say I have some simple logic like this:

let bool = false

const seven = 7
const arr = [1,2,3,4,5,6,7]
    
arr.forEach(element => {
    if (element === seven) {
        bool = true
    }
});

Now I wan't to call a function if "bool" has been set to true:

if (bool === true){
    doSomething()
}

Typescript gives an error in this case:

This condition will always return 'false' since the types 'false' and 'true' have no overlap.

Typescript complains even though logically I know that bool will be true by the time the condition block is triggered. How do I resolve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

俯瞰星空 2025-02-08 22:35:29

我不知道Typescript编译器会在这样的事情上抱怨,但是这再次是具有这样一种条件语句的一种奇怪的方式,因为:

if (bool === true)

但是

if (bool)

,您可以:

  1. 以正常方式写条件:<代码: if(bool){...} (强烈推荐)
  2. 迫使要为布尔值的类型: 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:

if (bool === true)

is the same as:

if (bool)

But yeah you can either:

  1. Write the condition in a normal way: if (bool) { ... } (highly recommended)
  2. Force the type to be boolean: if((bool as boolean) === true ) { ... } (it works but please don't do this)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文