如何使用null ts类型检查解决问题?

时间:2019-05-08 09:42:28

标签: javascript typescript types null

我具有可以为null的类的属性,在代码中,我正在检查value是否为null且为数组-向其推送新值,但类型检查器仍认为该值可以为null。有人可以解释为什么以及如何解决它,谢谢?

class BIT {
  head: BIT | null = this;
  private value: string;
  right: BIT | BIT[] | null = null;
  left: BIT | BIT[] | null = null;

  somefunction(node: BIT) {
    const haveLeft = this.left !== null;
    const leftIsBranch = haveLeft && this.left instanceof Array;

    if (haveLeft) {
      if (leftIsBranch) {
        this.left.push(node);
      }
    }
  }
}

UPD:如果我摆脱了布尔变量haveLeft和leftIsBranch并明确地将其添加到if语句中->一切正常。到底发生了什么事?

3 个答案:

答案 0 :(得分:1)

class BIT {
  head: BIT | null = this;
  private value: string;
  right: BIT | BIT[] | null = null;
  left: BIT | BIT[] | null = null; // below you try push: this.left.push(this.value). But your types it's BIT or Array of BIT or null, when 'this.value' is string. 

  somefunction() {
    const haveLeft = this.left !== null;
    const leftIsBranch = haveLeft && this.left instanceof Array;

    if (haveLeft) {
      if (leftIsBranch) {
        this.left.push(value); // you forgot to specify 'this': this.left.push(this.value);
      }
    }
  }
}

也可以代替example: null | BIT来指定example?: BIT

答案 1 :(得分:1)

在TypeScript中,所有类型默认情况下都可以为空:

  

默认情况下,null和undefined是所有其他类型的子类型。这意味着您可以将null和undefined分配给数字。

     

但是,当使用--strictNullChecks标志时,null和undefined仅可分配给void及其各自的类型。这有助于避免许多常见错误。如果要传递字符串或null或未定义,则可以使用联合类型string |。空|未定义。再一次,稍后会更多地讨论联合类型。

[来自TS docs]

因此,除非您使用--strictNullChecks编译器标志,否则不必添加| null

类型检查错误的原因可能是您正在检查null,而不是undefined-这是未初始化字段的默认值。松散的等式(!=而不是!==)检查应有助于识别未定义的情况:

const haveLeft = this.left != null; // This also excludes `undefined`

答案 2 :(得分:0)

请注意以下类型检查。

console.log(typeof null); // object
console.log(Array.isArray([])); // true