我在一个表单组上有这个条件:
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 岁,他就不能是
孙子
- 如果一个人小于 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")
如果 frType
是 Child
,则第二部分将为真,因此表达式的计算结果为 true
。如果 frType
是 Infant
,那么第一部分将为真,因此表达式的计算结果为 true
。如果 frType
既不是 Child
也不是 Infant
,那么第一部分将为真,表达式将再次, 评估为 true
- 逻辑错误,它总是解析为 true
。
(如果您为 Grandchild
和 Cousin
添加额外的 ||
条件,同样的事情会不断发生 - 它总是解析为 真
)
要么使用 &&
代替:
|| (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/