Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to test variable type or throw in TypeScript?

I want to have a function to test if a class variable is not null and use it in follow up function calls. But got TS complaints. Encapsulate this validate function because I need to call it in many of my methods.

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)
  }
}
like image 496
Mengo Avatar asked Oct 18 '25 14:10

Mengo


1 Answers

Typescript 3.7 introduces assertions in control flow analysis:

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

Playground

like image 50
Aleksey L. Avatar answered Oct 21 '25 05:10

Aleksey L.