Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.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 如何防止元组的并集变成并集的元组_Typescript - Fatal编程技术网

Typescript 如何防止元组的并集变成并集的元组

Typescript 如何防止元组的并集变成并集的元组,typescript,Typescript,尝试编写一个函数,当意外的“失败”发生时,该函数将优雅地返回。我想在这一个上使用go风格的函数return,并将返回键入[Val,null]|[null,Error] 但是,当尝试使用if语句键入返回值时 const [val, err] = myFunc(); // => [Val, null] | [null, Error] if (err) { handle(err); return; } // At this point in code, return value ha

尝试编写一个函数,当意外的“失败”发生时,该函数将优雅地返回。我想在这一个上使用go风格的函数return,并将返回键入
[Val,null]|[null,Error]

但是,当尝试使用if语句键入返回值时

const [val, err] = myFunc(); // => [Val, null] | [null, Error]

if (err) {
  handle(err);
  return;
}

// At this point in code, return value has to be of type [Val, null]

doSomethingWith(val) // Error! Type 'null' is not assignable to type 'Val'
如果使用类似的方法来处理对象,则看起来很混乱,()

看起来元组的并集变成了并集的元组

[Val,null]|[null,Error]

[Val | null,null | Error]


这是预期的行为吗?这是什么原因,有办法解决吗?

它没有变成一个联合元组-它变成了两个联合类型的变量,因为你把结果分成了两个变量。Typescript不会跟踪不同变量类型之间的依赖关系,因此变量
err
上的类型保护不会也不能缩小变量
val
的类型

解决方案:将函数的结果分配给单个变量而不进行分解,然后使用
result[0]
result[1]
引用其组件

const res = myFunc(); // => {type: 'Error'} | {type: 'Success', data: Val}


if (res.type === 'Error') {
  handle(res);
  return;
}

// In this example, res is correctly narrowed to {type: 'Success', data: Val}

doSomethingWith(res.data)