My goal is to create a variable that can either hold a number or be null. The purpose of this variability is to reset the variable at times by setting it to null. However, I am facing an issue where if I declare the variable with the type number | null
, I encounter difficulties using it as a number when needed.
Below is the sample code:
class Test {
start: number | null = null;
handler(e: Event) {
if (this.start === null) {
this.start = Date.now();
}
let time = Date.now() - this.start;
if (time < 1000) {
this.start = null;
}
// ...
}
}
The compiler raises a warning stating that this.start
"is possibly null". How can I affirm its validity? Alternatively, should I reconsider my approach and potentially use a boolean property like hasStarted
so that start
is consistently a number (or undefined)?