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)
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With