简体   繁体   English

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

[英]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.

相关问题 通过严格的空检查,如何在TypeScript中将类型为“:string | undefined”的变量转换为“:string”? - With strict null checks, how do I convert a variable that is of type “:string|undefined” to “:string” in TypeScript? Typescript:为什么不严格返回类型? - Typescript: why not strict return type? TypeScript严格的null检查:如何覆盖库约束? - TypeScript strict null checks: how to override library constraint? 带有严格空检查的 RegExpMatchArray 的 Typescript 类型定义 - Typescript type definition for RegExpMatchArray with a strict null check Typescript 类型断言和非 null 检查 - Typescript type assertions and non null checks 打字稿:严格检查“任何” - Typescript: Strict Checks Against "Any" TypeScript对数组中的对象字段进行严格的空检查 - TypeScript strict null check on field of object in array 为什么 typescript 在实现抽象函数时忽略严格的 null 检查? - Why does typescript disregard strict null checks when implementing abstract functions? 尽管有严格的空值检查,但未定义的非空文字字符串类型的未初始化字段是未定义的? - Uninitialized field with non-null literal string type is undefined despite strict null checks? 在严格的null检查中,可选属性内的属性的typescript类型 - typescript type of a property inside an optional property in strict null checking
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM