Flow Disjoint Unions with a default catch all

Flow Disjoint Unions with a default catch all

我想知道是否可以创建一个包罗万象的不相交联合类型。 我的想法是,如果说对象 'type' 字段是某个值,那么我知道我将有更多可用数据。

我认为它看起来像这样:

type MyObject =
  | { type: 'extra_details', moreDetails: {here: 'it is'} }
  | { type: string }

谢谢!

文档中有一章是关于标记联合的。 https://flowtype.org/docs/dynamic-type-tests.html#tagged-unions

但是像

这样的支票
  function foo(x: MyObject) {
      if (x.type === 'extra_details') {
         // ...extra details code-path
      }
  }

不足以证明在此代码路径中流,x只能是extraDetails类型。支票满足两种类型的并集。 {type: string}{type: 'extra_details'} 的更一般情况。但是,您可以改为检查是否存在额外字段。

  if (x.moreDetails) {

  }