测试变量类型的函数或在 TypeScript 中抛出?

Men*_*ngo 3 javascript typescript

我想要一个函数来测试类变量是否不存在null,并在后续函数调用中使用它。但遭到了 TS 的投诉。封装这个验证函数,因为我需要在许多方法中调用它。

class A {
  point: Point | null
  validatePoint() {
    if (!this.point) throw new Error()
  }

  update(p: Point | null) {
    this.validatePoint()
    // ts complains this.point can be null
    doSomething(this.point)
  }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_* L. 5

Typescript 3.7在控制流分析中引入了断言

class A {
    point: Point | null = null;
    validatePoint(): asserts this is { point: Point} {
        if (!this.point) throw new Error()
    }

    update(p: Point | null) {
        this.validatePoint()
        // now ts is sure that this.point can't be null
        doSomething(this.point)
    }
}
Run Code Online (Sandbox Code Playgroud)

操场