javascript - Flow type: either one property is required or the other
问题描述
I am trying to define a type in flow such that you must specify either a Client or an Invoice. This is my attempt at doing that:
type Client = {
client: {
id: number,
},
invoice?: {
id: number,
},
};
type Invoice = {
client?: {
id: number,
},
invoice: {
id: number,
},
};
type Props = Client | Invoice;
If client is undefined, then invoice must be defined and vice-versa.
However, when I try to access properties based on this, the flow typechecker throws errors:
function getAssignedId({client, invoice}: Props) {
return client ? client.id : invoice.id;
}
results in:
22: return client ? client.id : invoice.id;
^ Cannot get `invoice.id` because property `id` is missing in undefined [1].
References:
21: function getAssignedId({client, invoice}: Asssignement) {
^ [1]
Any idea why this is happening? Is there another way to achieve this with flow?
解决方案
当您通过以下方式解构类型时:
{client, invoice}: Props
这些变量的类型被解析。client
并且invoice
两者都已解决,?{ id: number }
因为它们当时可能存在也可能不存在。类型检查器不记得这两个对象是链接的,因为您已将它们分开。
如果不将它们分开,flow 可以跟踪联合类型并做正确的事情。
function getAssignedId(obj: Props) {
return obj.client ? obj.client.id : obj.invoice.id;
}
推荐阅读
- vue.js - 我什么时候可以信任我在 Vue 中的翻译内容?
- python - 正则表达式仅替换 Python 中的某些模式
- flutter - 在 Flutter 中弹出另一个页面后,Android 后退按钮未调用 onWillPop
- database - Magento 和 Vue Storefront 自定义数据库表
- javascript - 使用 Webpack 5 的正确设置是什么(webpack 新手)
- css - 在样式化组件中使用 Material-ui 主题
- python - TypeError:initial_value 必须是 str 或 None,而不是 _io.TextIOWrapper
- python - 无法在 anaconda 环境中导入 scikit-learn
- angular - 绑定动态更改的控件/在屏幕上呈现
- nlp - NLP 技术在语料库中查找相似关键字