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

时间:2017-08-04 17:52:02

标签: javascript flowtype

Flow问题似乎得不到什么答案,但这里有:

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"} : {}
  }
}

test的返回值最好是Derived*类型之一(Return1而不是Return2),其中conditional属性是一个布尔文字。

目的是让流程了解如果conditionaltrue,则对象test返回必须包含baz,反之亦然

这不可能吗?

1 个答案:

答案 0 :(得分:1)

Flow还不够聪明,无法为您解决问题。你必须做类似的事情:

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;
  }
}

此处有更多信息:https://flow.org/blog/2016/07/01/New-Unions-Intersections/