Reputation: 14219
I have the following code:
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]
So I tried
if fullname { const initials .... return ... } else return '';
Turns out typescript was complaining about this guy
fullname.replace(/[^a-zA-Z- ]/g, '')
Which makes sense because this might end up being an empty string
So I did
const t = fullname.replace(/[^a-zA-Z- ]/g, '')
if(t) { /* do the rest */ } else return ''
and it still gave me the object is possibly null error. I know it's not. How do I fix?
Upvotes: 3
Views: 10210
Reputation: 39
One possible solution to remove the null check error could be to use 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) || '';
}
This will return an empty string if the result of regex match is null
, otherwise will return the expected output.
You can try running it with different values in the TS playground here.
This has been explained in another answer here as well.
Upvotes: 0
Reputation: 2115
I run into a similar issue, in my case, all I did was to add the following rule to the tsconfig.json
"strictNullChecks": false
"noImplicitAny": false,
That should do the work
Upvotes: 5
Reputation: 1075427
The issue is that match
can return null
. If you want a blank string as as result, just use the ||
trick¹ to do || []
on the result of 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);
}
If you want to return null
in that case instead, you can use the &&
trick¹ to return the null
if the match
result is null
, otherwise continuing on with your join
etc.:
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);
}
¹ The ||
trick is that ||
evaluates its left-hand operand and, if it's truthy², takes that value as its result; otherwise it evaluates its right-hand operand and takes that value as its result. The &&
trick is similar, just the other way around: It evaluates its left-hand operand, and if it's falsy³, takes that value as its result; otherwise, it evaluates its right-hand operand and takes that value as its result.
² falsy - null
, undefined
, ""
, 0
, NaN
, or (of course) false
³ truthy - not falsy
Upvotes: 11