首页 > 解决方案 > 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]

You can try it here.

Any idea why this is happening? Is there another way to achieve this with flow?

标签: javascriptreactjsflowtype

解决方案


当您通过以下方式解构类型时:

{client, invoice}: Props

这些变量的类型被解析。client并且invoice两者都已解决,?{ id: number }因为它们当时可能存在也可能不存在。类型检查器不记得这两个对象是链接的,因为您已将它们分开。

如果不将它们分开,flow 可以跟踪联合类型并做正确的事情。

function getAssignedId(obj: Props) {
  return obj.client ? obj.client.id : obj.invoice.id;
}

试试流链接


推荐阅读