[英]Typescript error Object is possibly null? Why, how to disable?
我有以下代碼:
private extractInitials(fullname: string): string {
const initials = fullname
.replace(/[^a-zA-Z- ]/g, '')
.match(/\b\w/g)
.join('')
.toUpperCase();
return initials.substring(0, 2);
}
[ts] Object is possibly 'null'. [2531]
所以我嘗試if fullname { const initials.... return... } else return '';
結果打字稿在抱怨這個人
fullname.replace(/[^a-zA-Z- ]/g, '')
這是有道理的,因為這可能最終是一個空字符串
所以我做了
const t = fullname.replace(/[^a-zA-Z- ]/g, '')
if(t) { /* do the rest */ } else return ''
它仍然給了我 object is possibly null 錯誤。 我知道不是。 我該如何解決?
問題是match
可以返回null
。 如果您想要一個空字符串作為結果,只需使用||
技巧¹做|| []
|| []
match
結果:
private extractInitials(fullname: string): string {
const initials =
(fullname
.replace(/[^a-zA-Z- ]/g, '')
.match(/\b\w/g)
|| []
)
.join('')
.toUpperCase();
return initials.substring(0, 2);
}
如果您想在這種情況下返回null
,則可以使用&&
trick¹ 在match
結果為null
null
否則繼續您的join
等:
private extractInitials(fullname: string): string {
const parts = fullname
.replace(/[^a-zA-Z- ]/g, '')
.match(/\b\w/g);
return parts && parts.join('').toUpperCase().substring(0, 2);
}
¹ ||
訣竅是||
評估其左側操作數,如果它為真²,則將該值作為其結果; 否則,它計算其右側操作數並將該值作為結果。 &&
技巧是類似的,只是反過來:它計算它的左手操作數,如果它是假的³,就把那個值作為它的結果; 否則,它計算其右側操作數並將該值作為結果。
² falsy - null
、 undefined
、 ""
、 0
、 NaN
或(當然) false
³真實- 不虛假
我遇到了類似的問題,就我而言,我所做的就是將以下規則添加到 tsconfig.json
"strictNullChecks": false
"noImplicitAny": false,
那應該做的工作
消除空檢查錯誤的一種可能解決方案是使用Optional Chaining 。
const extractInitials = (fullname: string): string => {
const initials = fullname.replace(/[^a-zA-Z- ]/g, '').match(/\b\w/g)?.join('').toUpperCase();
return initials?.substring(0, 2) || '';
}
如果正則表達式匹配的結果為null
,這將返回一個空字符串,否則將返回預期的輸出。 您可以嘗試在此處的 TS 游樂場中使用不同的值運行它。
這也已在此處的另一個答案中進行了解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.