尝试编写一个在发生意外“失败”时优雅返回的函数。正在考虑使用 go 风格的函数 return 来 gonig,并将 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'
考虑到类似的对象方法效果很好,这似乎令人困惑,(链接到游乐场)
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)
似乎元组的并集变成了并集的元组,
from [Val, null] | [null, Error]
to [Val | null, null | Error]
这是预期的行为吗?这是什么原因,有什么办法可以解决吗?