【问题标题】:Typescript error Object is possibly null? Why, how to disable?打字稿错误对象可能为空?为什么,如何禁用?
【发布时间】:2019-05-12 17:52:02
【问题描述】:

我有以下代码:

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

它仍然给了我对象可能为空的错误。我知道不是。我该如何解决?

【问题讨论】:

  • match 可能为空,因此下划线所在的位置。
  • “这是有道理的,因为这最终可能是一个空字符串” 不,这没有意义。 "" 不是 null。它们是完全不同的东西。
  • 如果你确信源字符串是非空的,你可以在匹配结果上使用非空断言:.match(/\b\w/g)!——如果文本是空的,你会得到null从那和.join() 将抛出一个错误。

标签: javascript typescript


【解决方案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,你可以使用&&技巧¹返回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);
}

¹|| 的技巧是 || 评估其左侧操作数,如果 真实²,则将该值作为结果;否则,它会评估其右手操作数并将该值作为结果。 && 技巧与此类似,只是反过来:它计算左操作数,如果它是 falsy³,则将该值作为结果;否则,它会计算其右侧操作数并将该值作为结果。

² 虚假 - nullundefined""0NaN,或者(当然)false

³ 真实 - 不虚假

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,就我而言,我所做的只是将以下规则添加到 tsconfig.json

    "strictNullChecks": false
    "noImplicitAny": false,
    

    这应该做的工作

    【讨论】:

    • 谢谢。迄今为止最简单的解决方案:)
    【解决方案3】:

    消除空检查错误的一种可能解决方案是使用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 Playground here 中使用不同的值运行它。

    这已在另一个答案here 中进行了解释。

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 2019-09-04
      • 2023-01-20
      • 2022-01-08
      • 1970-01-01
      • 2017-10-12
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多