繁体   English   中英

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

[英]How to prevent a union of tuples turning into a tuple of unions?

尝试编写一个 function 在发生意外“故障”时优雅地返回。 正在考虑使用 go-style function return on this 的 gonig,并将 return 键入为[Val, null] | [null, Error] [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'

考虑到对象的类似方法工作得很好,似乎令人困惑,( 链接到操场

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)

似乎元组的并集变成了并集的元组,

来自[Val, null] | [null, Error] [Val, null] | [null, Error]

[Val | null, null | Error] [Val | null, null | Error]

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

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

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

您的代码现在可以在 TypeScript 4.6 beta 上正常工作。

操场上的演示

TS 4.6 beta 公告中有关“相关参数的控制流分析”的信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM