如何在 Javascript(和 Flow)中使用条件访问根据键对对象列表进行排序?

How do I sort a list of objects based on key with conditional access in Javascript (and Flow)?

所以我有一个项目列表

const items = this.props.complex_object?.items;

我想根据一个键对这些项目进行排序。我自然想执行以下操作

const sortedItems = this.props.complex_object?.items.sort(
  (a, b) => a?.confidence > b?.confidence
);

但我收到以下流程错误。

Flow does not yet support method or property calls in optional chains.

这有点道理,因为 items 属于流类型 ?Array<ItemType>。鉴于 Items 存在的条件性质,我尝试检查 null 和 undefined

var items = this.props.complex_object?.items;

if (items === null || items === undefined)
  items = [];

const sortedItems = items.sort((a, b) => a. confidence > b.confidence);

return (<Table items=sortedItems>);

但这并不能缓解问题。最重要的是,我如何对可选对象数组进行排序?

非常感谢

如果你知道props.complex_object将永远存在,你可以

var items = this.props.complex_object.items || [];

如果 items 在您的 complex_object 中不存在(未定义),或者存在但值为 undefinednull,那么它将默认为空数组。