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

Viewed 891

I use a package that has a function with the following declaration:

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

I tried to destructure the returned value from a call to this function with:

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

but it does not work probably due to the 'void' part. Using a temp value works, but looks clumsy.

const temp = await getList(some_params);

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

Just wonder there is better ways for destructuring in this case. Thanks.

1 Answers

Indeed, we can't destructure void/undefined and it's a good thing: it's necessary to handle also the case when void is returned, in your example with a guard clause if not undefined then ...

If you want your code to focus on the happy path and avoid temporary variable, you can use the Maybe type (npm) and its method map():

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