0

Here is a snippet of TypeScript code:

if (props.categories && props.categories.length > 0) {
  // code...
}

props.categories is defined like this:

interface MyComponentProps {
  categories?: string[];
}

I'm a little confused about the ? operator here...I would think that I could shorten my conditional to:

if (props.categories?.length > 0) {
  // code...
}

But, TypeScript complains that "Object is possibly undefined". Why is this?

3
  • The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 19, 2021 at 17:55
  • What do you mean by "still" in "still complains"? I can't reproduce any problem with your first line, as shown here. Please consider modifying the code in this question so as to constitute a minimal reproducible example which, when dropped into a standalone IDE like The TypeScript Playground (link), clearly demonstrates the issue you are facing. This will allow those who want to help you to immediately get to work solving the problem without first needing to re-create it. And it will make it so that any answer you get is testable against a well-defined use case. Commented Aug 19, 2021 at 18:05
  • @jcalz yep, "still" was the wrong word, thanks for pointing that out, I edited the question. Federkun's answer below cleared up my confusion Commented Aug 19, 2021 at 18:09

1 Answer 1

1

props.categories?.length > 0 may resolve to undefined > 0 which is the origin of the error. So, it's not strictly the same as props.categories && props.categories.length > 0.

My suggestion is to keep it as it is. If you really really want to use the optional chaining operator here, you may just need to default to a number to compare

props.categories?.length ?? 0 > 0

But, this is not any better.

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

Comments

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.