代码之家  ›  专栏  ›  技术社区  ›  alim1990

类型脚本错误此条件将始终返回“true”,因为类型没有重叠

  •  2
  • alim1990  · 技术社区  · 6 年前

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

    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")))
    

    它包含三个主要条件:

    1. infant
    2. 如果一个人超过40岁,他就不能成为 grandchild
    3. 如果一个人少于5年,他应该 child , , 孙子 cousin .

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

    我收到的错误是:

    “Child”和“baby”没有重叠。[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);
    
    1 回复  |  直到 6 年前
        1
  •  7
  •   CertainPerformance    6 年前

    考虑独立表达式:

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

    如果 frType Child true . 如果 frType型 Infant 真的 frType型 儿童 也不是 婴儿 真的 -逻辑是错误的,它总是会解决 .

    (如果您添加了 || 条件 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))