简体   繁体   English

TypeScript strictNullChecks - 对象可能是'null'

[英]TypeScript strictNullChecks - Object is possibly 'null'

After enabling strictNullChecks with Angular 4.1.1, getting several errors for null checks. 在使用Angular 4.1.1启用strictNullChecks之后,为null检查获取了几个错误。 I have fixed bundles of them but unable to fix the same Object is possibly 'null' for this.form.get('username').value . 我已修复它们的捆绑但无法修复相同的Object is possibly 'null'对于this.form.get('username').value Object is possibly 'null' Likewise others, I have tried the same but unable to fix the error. 与其他人一样,我尝试了同样但无法修复错误。

if (this.form.get('username') != null) {
    body.append('username', this.form.get('username').value);
}

尝试使用非空断言运算符

this.form.get('username')!.value; // notice !

You really don't need to cast here. 你真的不需要在这里施展。 You actually never have to. 你实际上从来没有。

The most compact way to do it: 最紧凑的方式:

const username = this.form.get('username');
if (username) body.append('username', username.value);

Or in exit-early style: 或者退出早期风格:

const username = this.form.get('username');
if (!username) return;
# back to normal flow
body.append('username', username.value); // no complaint, username cannot be falsy, then it must be { value: string }

The compiler cannot infer that this.form.get('username') hasn't change between the null check and the time you use .value on it. 编译器无法推断this.form.get('username')null检查和你使用.value的时间之间没有变化。

With a const variable, it can. 使用const变量,它可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM