2

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

0

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

2 Comments

In the second line, you misplaced the ?
I actually misplaced it on the first line, good catch. Fixed.
0

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

language!.toLowerCase().includes(selectedCategory)

Comments

-1

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.

1 Comment

I wouldn't recommend this. It's possible it'll lead to a slight performance benefit in older browsers (see here), but optional chaining realistically is never going to be a performance bottlneck. Working with the compiler instead of against it, and getting type safety, is much more important in practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.