Jonathan.Brink
Jonathan.Brink

Reputation: 25403

TypeScript: inline null check confusion, not working in particular usage

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?

Upvotes: 0

Views: 459

Answers (1)

Federkun
Federkun

Reputation: 36954

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.

Upvotes: 1

Related Questions