繁体   English   中英

打字稿错误对象可能为空? 为什么,如何禁用?

[英]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 - nullundefined""0NaN或(当然) 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM