我在表单组上有这种情况:
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个主要条件:
- 如果17岁的人,不能设置为
infant
- 如果一个人大于40,他不能是
grandchild
- 如果一个人小于 5 岁,他应该是
child
,infant
,grandchild
或cousin
如果这些条件之一为真,我将发送一条错误消息。
我收到的错误是:
[ts] 此条件将始终返回 ‘true’,因为类型 ‘“Child”’ 和 ‘“Infant”’ 没有重叠。 [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);
原文由 alim1990 发布,翻译遵循 CC BY-SA 4.0 许可协议
考虑独立表达式:
如果
frType
是Child
,则第二部分将为真,因此表达式将计算为true
。如果frType
是Infant
,那么第一部分将为真,因此表达式将计算为true
。 IffrType
is neitherChild
norInfant
, then the first part will be true, and the expression will, again, evalute totrue
- 逻辑有问题,它总是会解析为true
。(If you add additional
||
conditions forGrandchild
andCousin
, the same thing keeps happening - it’ll always resolve totrue
)使用
&&
代替:或者,为了使逻辑更容易理解,您可以考虑使用数组,并使用
.includes
: