javascript - typescript 错误此条件将始终返回 'true',因为类型没有重叠

标签 javascript angular typescript typescript2.0

我在一个表单组上有这个条件:

if((age>17 && (this.frType=="Infant")) 
|| (age>40 && this.frType=="Grandchild")
|| (age<=5 && 
   (this.frType!="Child" 
   || this.frType!="Infant" 
   || this.frType!="Grandchild" || this.frType!="Cousin")))

它包含3个主要条件:

  1. 如果是 17 岁的人,则不能设置为infant
  2. 如果一个人超过 40 岁,他就不能是孙子
  3. 如果一个人小于 5 岁,他应该是 child 婴儿孙子堂兄弟 .

如果其中一个条件为真,我将发送一条错误消息。

我收到的错误是:

[ts] This condition will always return 'true' since the types '"Child"' and '"Infant"' have no overlap. [2367]

if 条件的这一部分:

|| this.frType!="Infant" || this.frType!="Grandchild" || this.frType!="Cousin")))

我在不同的组件中使用了确切的条件,但它没有显示错误。

if((age>17 && (this.family_relation_type=="Infant")) 
|| (age>40 && this.family_relation_type=="Grandchild")
|| (age<=5 && 
   (this.family_relation_type!="Child" || 
    this.family_relation_type!="Infant" || 
    this.family_relation_type!="Grandchild" || 
    this.family_relation_type!="Cousin")))

下面是我如何计算这两个部分的年龄:

let timeDiff = Math.abs(Date.now() - this.formGroup.controls['dob'].value);
let age = Math.floor((timeDiff / (1000 * 3600 * 24))/365);

最佳答案

考虑独立表达式:

(this.frType!="Child" || this.frType!="Infant")

如果 frTypeChild,则第二部分将为真,因此表达式的计算结果为 true。如果 frTypeInfant,那么第一部分将为真,因此表达式的计算结果为 true。如果 frType 既不是 Child 也不是 Infant,那么第一部分将为真,表达式将再次, 评估为 true - 逻辑错误,它总是解析为 true

(如果您为 GrandchildCousin 添加额外的 || 条件,同样的事情会不断发生 - 它总是解析为 )

要么使用 && 代替:

|| (age<=5 && (
   this.frType!="Child" 
   && this.frType!="Infant" 
   && this.frType!="Grandchild"
   && this.frType!="Cousin"
 ))

或者,为了使逻辑更容易理解,您可以考虑使用数组,并使用 .includes:

const kidsFiveAndUnder = ['Child', 'Infant', 'Grandchild', 'Cousin'];
// ...
|| (age <= 5 && !kidsFiveAndUnder.includes(this.frType))

关于javascript - typescript 错误此条件将始终返回 'true',因为类型没有重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53719693/

相关文章:

javascript - 使用 key 在多个项目之间插入分隔符

javascript - 页面刷新后如何保持onclick功能

javascript - 如何在 Angular 6 中使用 ngFor 循环 JSON 对象

typescript - TS 子类中调用 super() 的目的是什么?

typescript - 我可以有一个对象枚举吗?

javascript - 使用 JQuery Mobile 进行多页面设计的问题

javascript - 使用 LESS 检测浏览器版本

html - 错误类型错误 : Cannot read property 'nativeElement' of undefined

Angular Subscribe - 类型 'Subscription' 缺少类型 'ToDo[]' : length, pop、push、concat 等 26 个属性的以下属性

javascript - '+' 在 AngularJS 中执行连接而不是加法