打字稿错误此条件将始终返回“真”,因为类型没有重叠

新手上路,请多包涵

我在表单组上有这种情况:

 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,他不能是 grandchild
  3. 如果一个人小于 5 岁,他应该是 child , infant , grandchildcousin

如果这些条件之一为真,我将发送一条错误消息。

我收到的错误是:

[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 许可协议

阅读 742
2 个回答

考虑独立表达式:

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

如果 frTypeChild ,则第二部分将为真,因此表达式将计算为 true 。如果 frTypeInfant ,那么第一部分将为真,因此表达式将计算为 true 。 If frType is neither Child nor Infant , then the first part will be true, and the expression will, again, evalute to true - 逻辑有问题,它总是会解析为 true

(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

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

原文由 CertainPerformance 发布,翻译遵循 CC BY-SA 4.0 许可协议

在我的例子中,我使用了一个名为 type 的类型作为按钮元素 React.ComponentPropsWithRef<'button'>

 type ButtonProps = {
  type?: 'submit' | 'button' | 'link'; // ❌
} & React.ComponentPropsWithRef<'button'>;

type 被覆盖,因为 React.ComponentPropsWithRef<'button'> 也有 type 。我用 elementType 替换它,问题就解决了。

 type ButtonProps = {
  elementType?: 'submit' | 'button' | 'link'; // ✅
} & React.ComponentPropsWithRef<'button'>;

原文由 doğukan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题