Typescript is alerting you to a potential bug in your code. It seems that the type of your array is structured as follows:
({ name: string } | undefined)[]
This indicates that when you loop through the array, you must account for cases where the item may be undefined
. Failure to do so could result in a runtime error when trying to access (undefined).name
.
An effective solution is to filter out any undefined values from your array:
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 approach utilizes a filter function acting as a typeguard. Once applied, the resulting array will be of type MyItem[]
, enabling successful sorting knowing all items contain a value.
Playground