简体   繁体   English

FlowJS:如何使用联合类型和布尔文字

[英]FlowJS: How to use union types and boolean literals

Flow questions seem to garner few answers, but here goes: 流程问题似乎没有多少答案,但是可以这样:

type Base = {
  foo: string,
  bar: string
}
type Derived1 = Base & {
  conditional: false
}
type Derived2 = Base & {
  conditional: true,
  baz: string
}

type One = {
  foo: string,
  bar: string,
  conditional: boolean
}
type Two = One & {
  baz: string
}

type Return1 = Derived1 | Derived2  // fails

type Return2 = One | Two  // works, but not desired

function test(conditional: boolean): Return1 {
  return {
    foo: "foo",
    bar: "bar",
    conditional,
    ...conditional ? {baz: "baz"} : {}
  }
}

It is preferable for the return value of test to be one of the Derived* types ( Return1 rather than Return2 ), where the conditional property is a boolean literal. test的返回值最好是Derived*类型之一( Return1而不是Return2 ),其中conditional属性是布尔文字。

The intention is for flow to understand that if conditional is true , then the object test returns must contain baz and vice versa. 这样做的目的是让流程理解,如果conditionaltrue ,那么对象test返回的结果必须包含baz ,反之亦然。

Is this not possible? 这不可能吗?

Flow isn't quite smart enough to figure it out for you. Flow不够智能,无法为您解决。 You have to do something like: 您必须执行以下操作:

function test(conditional: boolean): Return1 {

  const base = {
    foo: "foo",
    bar: "bar",
  }

  if (!conditional) {
    return Object.assign({}, base, { conditional });
  } else {
    const result: Derived2 = Object.assign({}, base, { conditional }, {baz: "baz"});
    return result;
  }
}

More info here: https://flow.org/blog/2016/07/01/New-Unions-Intersections/ 此处了解更多信息: https : //flow.org/blog/2016/07/01/New-Unions-Intersections/

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

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