【发布时间】: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