網站搜尋

javascript - Typescript 錯誤:物件可能為 null?為什麼,如何停用?


我有以下程式碼:

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 '';

結果 TypeScript 對這傢伙發出了抱怨

fullname.replace(/[^a-zA-Z- ]/g, '')

這很合理,因為這最終可能會是一個空字串

所以我做了

const t = fullname.replace(/[^a-zA-Z- ]/g, '')
if(t) { /* do the rest */ } else return ''

但它仍然給我「物件可能為空」的錯誤。我知道不是。我要怎麼修復?

答案#1

問題是 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,你可以使用 && 技巧¹,在 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);
}

¹ || 的技巧是 || 會先計算其左邊的運算元,如果它是 truthy²,就取該值作為結果;否則,它會計算右邊的運算元,並取該值作為結果。&& 的技巧類似,只是方向相反:它先計算左邊的運算元,如果它是 falsy³,就取該值作為結果;否則,它會計算右邊的運算元,並取該值作為結果。

² falsy - null、undefined、""、0、NaN,或(當然)false

³ truthy - 不為假

答案#2

我遇到了類似的問題,就我而言,我所做的只是將以下規則添加到 tsconfig.json 中

"strictNullChecks": false
"noImplicitAny": false,

那應該可以完成工作