javascript - FlowJS : How to use union types and boolean literals

标签 javascript flowtype

心流问题似乎没有什么答案,但这里是:

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 属性是 bool 值。

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

这不可能吗?

最佳答案

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/

关于javascript - FlowJS : How to use union types and boolean literals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45512807/

相关文章:

javascript - 以字符串作为第一个操作数的加法运算符可以返回非字符串吗?

javascript 对象 - 使用递归函数动态设置嵌套值

javascript - 使用 jQuery 但具有同一类的多个元素设置元素的 html 内容

javascript - Extjs/Javascript - 在函数返回之前等待 MessageBox 响应

javascript - 为什么流无法在这个函数式 Either 示例中更准确地确定类型?

typescript - 到 TypeScript 迁移的流程

javascript - jquery : animate list scrollLeft/scrollRight on mouse wheel

javascript - 如何仅禁用 chrome 中的 "debugger"关键字,该关键字由循环内的 eval 执行?

javascript - Flow Error Out 中的 Webpack 路径

generics - 如何在流程中显式地将类型参数传递给泛型函数?