Reputation: 11
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));
Upvotes: 1
Views: 5799
Reputation: 187034
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.
Upvotes: 4