Typescript error对象可能为null?为什么,如何禁用?

Aso*_*ool 1 javascript typescript

我有以下代码:

private extractInitials(fullname: string): string {
    const initials = fullname
        .replace(/[^a-zA-Z- ]/g, '')
        .match(/\b\w/g)
        .join('')
        .toUpperCase();
    return initials.substring(0, 2);
}
Run Code Online (Sandbox Code Playgroud)

我收到了一个错误 在此输入图像描述

[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 ''
Run Code Online (Sandbox Code Playgroud)

它仍然给了我对象可能是null错误.我知道不是.我该如何解决?

T.J*_*der 5

问题是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);
}
Run Code Online (Sandbox Code Playgroud)

如果你想返回null在这种情况下,而不是,您可以使用&&trick¹返回null.如果match结果是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);
}
Run Code Online (Sandbox Code Playgroud)

¹ ||诀窍在于||评估其左手操作数,如果它是真实的,则将该值作为结果; 否则它会评估其右侧操作数并将该值作为结果.该&&诀窍是相似的,只是周围的其他方法:它评估其左边的操作,如果它是falsy ³,采用该值作为其结果; 否则,它会评估其右侧操作数并将该值作为结果.

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

³ 真理 - 不是假的