Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with Array shift return type in Typescript 2.0 with strict null checks

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

like image 467
Roaders Avatar asked Dec 09 '16 20:12

Roaders


2 Answers

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

like image 153
artem Avatar answered Oct 12 '22 23:10

artem


Have you made sure that _timers has been initialized?
For example:

private _timers: ITimer[] = [];

Or in the constructor:

constructor() {
    this._timers = [];
    ...
}
like image 37
Nitzan Tomer Avatar answered Oct 13 '22 01:10

Nitzan Tomer