空值類型檢查
P粉896751037
2023-08-03 11:34:29
<p>我剛剛在服務中編寫了一個方法,但是遇到了類型提示我可能返回空值的問題,儘管我已經在if語句區塊中進行了空值檢查。 </p>
<pre class="brush:php;toolbar:false;">public async getUserById(id: string): Promise<UserEntity> {
const user = this.userRepository.getById(id); // returns <UserEntity | null>
if (!user) { // checking for null
throw new NotFoundUser(`Not found user`);
}
// Type 'UserEntity | null' is not assignable to type 'UserEntity'.
// Type 'null' is not assignable to type 'UserEntity'.
return user;
}</pre>
<p>如果使用者變數為空,我希望拋出異常,如果不為空,則回傳UserEntity。 <br /><br />如果我在那裡輸入兩個驚嘆號,問題就解決了。 </p><p><br /></p>
<pre class="brush:php;toolbar:false;">if (!!user) { // checking for null
throw new NotFoundUser(`Not found user`);
}</pre>
<p>但如果我在控制台中輸入!!null,它將返回false,所以在這種情況下,我永遠不會進入拋出異常的情況。為什麼會出現這種行為? </p>
因為 !! 類似 Boolean,所以在這行程式碼中,你做了類似 Boolean(null) 的操作,所以你會得到 false,因為在布林值中,null 是 false。你可以使用 user === null 來檢查是否為 null。
#