Typescript错误,因为类型没有重叠,所以此条件将始终返回"true" [英] Typescript error This condition will always return 'true' since the types have no overlap
问题描述
我在表单组中有此条件:
I having this condition on a form group:
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
.
- If a person aged 17, cannot be set to
infant
- If a person is bigger than 40, he cannot be a
grandchild
- If a person is less than 5 years, he should be
child
,infant
,grandchild
orcousin
.
如果满足以下条件之一,我将发送一条错误消息.
If one of these conditions is true, I will send an error message.
我收到的错误是:
[ts]由于类型 '"Child"'和'"Infant"'没有重叠. [2367]
[ts] This condition will always return 'true' since the types '"Child"' and '"Infant"' have no overlap. [2367]
关于if
条件的这一部分`:
On this part of the if
condition`:
|| this.frType!="Infant" || this.frType!="Grandchild" || this.frType!="Cousin")))
我在其他组件中使用的是确切条件,并且没有显示错误.
I am using the exact condition in a different component, and it does not show an error.
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")))
这是我计算这两个部分的年龄的方法:
Here is how I am calculating the age in both components:
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,因此表达式的计算结果为true
.如果frType
是Infant
,则第一部分为true,因此表达式的计算结果为true
.如果frType
既不是 Child
也不是Infant
,则第一部分将为true,并且表达式将再次求值到true
-逻辑错误,它将始终解析为<c9>.
If frType
is Child
, the second part will be true, so the expression will evaluate to true
. If frType
is Infant
, then the first part will be true, so the expression will evaluate to true
. If frType
is neither Child
nor Infant
, then the first part will be true, and the expression will, again, evalute to true
- the logic is faulty, it'll always resolve to true
.
(如果为Grandchild
和Cousin
添加其他||
条件,同一件事不断发生-它将始终解析为<c9>)
(If you add additional ||
conditions for Grandchild
and Cousin
, the same thing keeps happening - it'll always resolve to true
)
请改用&&
:
|| (age<=5 && (
this.frType!="Child"
&& this.frType!="Infant"
&& this.frType!="Grandchild"
&& this.frType!="Cousin"
))
或者,为了使逻辑更容易理解,您可以考虑使用数组,然后使用.includes
:
Or, to make the logic easier to follow, you might consider using an array, and use .includes
:
const kidsFiveAndUnder = ['Child', 'Infant', 'Grandchild', 'Cousin'];
// ...
|| (age <= 5 && !kidsFiveAndUnder.includes(this.frType))
这篇关于Typescript错误,因为类型没有重叠,所以此条件将始终返回"true"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!