简体   繁体   中英

Typescript error Object is possibly null? Why, how to disable?

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);
}

I'm getting an error在此处输入图像描述

[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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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