1

I have an array of objects that I'm sorting by the value of one of the properties. The sort is working correctly but I'm getting a Typescript warning that "Object is possibly 'undefined'"

How do I check for undefined values on name to resolve this warning?

myItems.sort((a, b) => (a.name > b.name  ? 1 : -1));

1 Answer 1

4

Typescript is telling you there is a bug in your code. The type of your array apparently is something like:

({ name: string } | undefined)[]

That means that when you iterate over that array, you need to handle the case where the item is undefined, otherwise (undefined).name will throw a runtime error.


The easiest way to fix this is probably to filter your array so it no longer includes any undefined values:

interface MyItem { name: string }

const myItems: (MyItem | undefined)[] = [
  { name: 'c' },
  { name: 'b' },
  undefined,
  { name: 'a' },
]

myItems
  .filter((item): item is MyItem => !!item)
  .sort((a, b) => (a.name > b.name  ? 1 : -1));

This uses a filter function that is also a typeguard. After it runs, the returned array will be of type MyItem[], and then your sort can run correctly knowing that all items have a value.

Playground

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.