Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript destructure从函数返回的值可以是void或对象_Typescript_Destructuring - Fatal编程技术网

Typescript destructure从函数返回的值可以是void或对象

Typescript destructure从函数返回的值可以是void或对象,typescript,destructuring,Typescript,Destructuring,我使用的包具有以下声明的函数: const getList: (params?: ListRequestParams | undefined) => Promise<void | { items: any[]; pageInfo: PageInfo; }> 但它不起作用可能是因为“无效”部分。使用临时值是可行的,但看起来很笨拙 const temp = await getList(some_params); if(temp !== undefined) {

我使用的包具有以下声明的函数:

const getList: (params?: ListRequestParams | undefined) => Promise<void | {
    items: any[];
    pageInfo: PageInfo;
}>
但它不起作用可能是因为“无效”部分。使用临时值是可行的,但看起来很笨拙

const temp = await getList(some_params);

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

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

事实上,我们不能对
void
/
未定义的
进行解构,这是一件好事:在您的示例中,当返回
void
时,还需要处理这种情况,如果未定义,则使用保护子句

如果您希望代码关注快乐路径并避免临时变量,则可以使用
Maybe
type()及其方法
map()


当传递
params
对象时,它总是返回一个值,当没有
params
时,它总是返回
void
,还是参数和返回类型无关?如果它们是相关的,那么我们可以通过对函数应用更好的类型(通过合并或包装声明)来解决这个问题。getList从可能不返回任何数据的远程服务器读取数据(网络错误,…)。我的代码只是项目中的一小部分,我不想对函数原型进行更改。我看不出您的代码有任何问题(尽管我会使用比
temp
更好的名称,例如
response
result
:D),但您不能对可能无效的内容进行分解。Romain Deneau建议使用像
Maybe
这样的类型,这也是一个好主意,因为它可以让您忽略一个事实,即值可以为null/未定义,直到稍后可以使用像
valueOrGet
()我不熟悉JavaScript/TypeScript,只是想知道是否有一些奇特的单行类型转换可以将返回分解为两个有效对象或两个“未定义”对象。我将坚持使用临时变量。它更具可读性。但很高兴了解这种类型。谢谢
const temp = await getList(some_params);

if(temp !== undefined)
{
  const { items, pageInfo } = temp;
}
Maybe
  .ofNullable(await getList(some_params))
  .map(({ items, pageInfo }) => { /*...*/ });