In my Typescript 2.0 project with strict null checks I have an array:
private _timers: ITimer[]
and an if statement:
if(this._timers.length > 0){
this._timers.shift().stop();
}
but I get a compile error:
Object is possibly 'undefined'
How can I convince the compiler that it's not undefined?
I can get round it like this:
const timer = this._timers.shift();
if(timer){
timer.stop();
}
but that seems a bit too verbose and a needless use of a variable just to get round the typing constraints.
Thanks
There is non-null assertion operator, mentioned in 2.0 release notes (and will appear in the documentation soon), intended for cases exactly like this. It's postfix !
, and it suppresses this error:
if(this._timers.length > 0){
this._timers.shift()!.stop();
}
See also https://stackoverflow.com/a/40350534/43848
Have you made sure that _timers
has been initialized?
For example:
private _timers: ITimer[] = [];
Or in the constructor:
constructor() {
this._timers = [];
...
}
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