2017-05-05 51 views
1

在啓用strictNullChecks與Angular 4.1.1之後,獲取null檢查的多個錯誤。我已經修復了它們的捆綁,但無法修復的this.form.get('username').value。與其他人一樣,我也嘗試過,但無法修復錯誤。TypeScript strictNullChecks - 對象可能爲'null'

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

回答

0

你真的不需要在這裏施展。你其實從來沒有必要。

最緊湊的方式做到這一點:

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

還是在出口早期風格:

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 } 

編譯器不能推斷this.form.get('username')已經不是null檢查與時間的變化你使用.value就可以了。

使用const變量,它可以。