Typescript 解构函数的返回值,可以是 void 或对象

Typescript destructure returned values from function which can be either void or an object

我使用的包具有以下声明的功能:

const getList: (params?: ListRequestParams | undefined) => Promise<void | {
    items: any[];
    pageInfo: PageInfo;
}>

我试图通过以下方式解构调用此函数的返回值:

const {items, pageInfo} = await getList(some_param);

但它不起作用可能是由于 'void' 部分。使用临时值可行,但看起来很笨拙。

const temp = await getList(some_params);

if(temp !== undefined)
{
  const { items, pageInfo } = temp;
}

只是想知道在这种情况下是否有更好的解构方法。谢谢

确实,我们无法解构 void/undefined,这是一件好事:还需要处理返回 void 的情况,在您的示例中保护条款 if not undefined then ...

如果你希望你的代码专注于快乐路径并避免临时变量,你可以使用 Maybe 类型 (npm) 及其方法 map():

Maybe
  .ofNullable(await getList(some_params))
  .map(({ items, pageInfo }) => { /*...*/ });