Johnny
Johnny

Reputation: 291

React Typescript: Object is possibly 'undefined'

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

Upvotes: 2

Views: 6613

Answers (5)

Nathan
Nathan

Reputation: 78529

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

Upvotes: 1

Sanket Shah
Sanket Shah

Reputation: 3091

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.

Upvotes: 1

Hamed Siaban
Hamed Siaban

Reputation: 1681

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

language!.toLowerCase().includes(selectedCategory)

Upvotes: 0

Nicholas Obert
Nicholas Obert

Reputation: 1628

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.

Upvotes: -1

DariushStony
DariushStony

Reputation: 173

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

Upvotes: 2

Related Questions