[英]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: 在我的具有严格空检查的Typescript 2.0项目中,我有一个数组:
private _timers: ITimer[]
and an if statement: 和if语句:
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. 有一个非空断言运算符 ,在2.0发行说明中提到(并将很快出现在文档中 ),用于与此类似的情况。 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 另请参见https://stackoverflow.com/a/40350534/43848
Have you made sure that _timers
has been initialized? 你确定
_timers
已经初始化了吗?
For example: 例如:
private _timers: ITimer[] = [];
Or in the constructor: 或者在构造函数中:
constructor() {
this._timers = [];
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.