Home > Net >  React Typescript: Object is possibly 'undefined'
React Typescript: Object is possibly 'undefined'

Time:07-31

I'm using react with typescript and was getting Object is possibly 'undefined' error when return language.toLowerCase().includes(selectedCategory) so I added a checking as in below. Error is gone but I'm not sure whether It can impact the performance. Please advice.

import { filter } from 'lodash';
...
return filter(channels, ({
    language
}: Channels) => {
    if (
        language &&
        language.toLowerCase() !== selectedCategory &&
        selectedCategory !== 'all'
    ) {
        return false;
    }
    return (
        language && language.toLowerCase().includes(selectedCategory)
    );
});

CodePudding user response:

You can use Optional Chaining instead.

If the language is not null or undefined (nullish) it will access the property or method you want otherwise it will return undefined

CodePudding user response:

If you're damn sure about language that it can't be null or undefined then use ! operator (non-null assertion operator) and rewrite your code like this:

import { filter } from 'lodash';
...
return filter(channels, ({
    language
}: Channels) => {
    return language!.toLowerCase().includes(selectedCategory);
});

Or You can use Optional Chaining instead.

CodePudding user response:

No, that will not impact performance in any way, that's an incredibly inexpensive and common type of check to performance.

You can simplify it though with optional chaining

If you write language?.toLowercase(), it will evaluate to undefined if language is undefined, and a lowercase language if it is defined. So:

if (
        language?.toLowerCase() !== selectedCategory &&
        selectedCategory !== 'all'
    ) {
        return false;
    } else { 
       return language?.toLowerCase().includes(selectedCategory)
    }

CodePudding user response:

If you are sure that the object value is never null or undefined, You can use ! mark:

language!.toLowerCase().includes(selectedCategory)

CodePudding user response:

If you are sure that language will never be undefined, you can use the ! non-null assertion operator to remove that warning.

language!.toLowerCase()

This is the best option in terms of runtime performance since when the code is transpiled into JavaScript the assertion operator is just removed.

  • Related