使用严格的空检查处理Typescript 2.0中的数组移位返回类型

Roa*_*ers 4 typescript typescript2.0

在我的具有严格空检查的Typescript 2.0项目中,我有一个数组:

private _timers: ITimer[]

和if语句:

if(this._timers.length > 0){
  this._timers.shift().stop();
}
Run Code Online (Sandbox Code Playgroud)

但我得到一个编译错误:

Object is possibly 'undefined'

我怎样才能说服编译器它没有未定义?

我可以像这样绕过它:

const timer = this._timers.shift();
if(timer){
  timer.stop();
}
Run Code Online (Sandbox Code Playgroud)

但这似乎有点过于冗长,并且不必要地使用变量来绕过打字约束.

谢谢

art*_*tem 5

有一个非空断言运算符,在2.0发行说明中提到(并将很快出现在文档中),用于与此类似的情况.这是后缀!,它抑制了这个错误:

    if(this._timers.length > 0){
        this._timers.shift()!.stop();
    }
Run Code Online (Sandbox Code Playgroud)

另请参见/sf/answers/2824537411/