Reputation: 5332
After enabling strictNullChecks
with Angular 4.1.1, getting several errors for null
checks. I have fixed bundles of them but unable to fix the same Object is possibly 'null'
for this.form.get('username').value
. 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);
}
Upvotes: 15
Views: 19190
Reputation: 3661
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.
With a const
variable, it can.
Upvotes: 3
Reputation: 214275
Try using Non-null assertion operator like
this.form.get('username')!.value; // notice !
Upvotes: 37