簡體   English   中英

FlowJS:如何使用聯合類型和布爾文字

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

流程問題似乎沒有多少答案,但是可以這樣:

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 ,反之亦然。

這不可能嗎?

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM