【问题标题】:Why Typescript complains that I cannot compare two boolean variables when they are of different value (true,false)? [duplicate]为什么 Typescript 抱怨当它们具有不同的值(真,假)时我无法比较两个布尔变量? [复制]
【发布时间】:2022-02-18 22:27:59
【问题描述】:

正如您在下图中的示例中看到的那样,在尝试将布尔类型的变量与 true 进行比较时,我们会遇到这个奇怪的错误。

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

有谁知道我们为什么会收到这个错误,或者我们错过了什么? 谢谢!

【问题讨论】:

标签: angular typescript


【解决方案1】:

您可以显式转换回boolean 以解决问题limitReached as boolean

let items = [1, 2, 3];
let limitReached: boolean = false;

items.forEach(v => {
    if (v == 2) {
        limitReached = true;
    }
});

if ((limitReached as boolean) == true) {
    console.log("true")
}

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 2014-06-19
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多