簡體   English   中英

FlowType:多種類型的通用繼承

[英]FlowType: Generic inheritance of multiple types

想象一下,有兩種數據類型,它們都有一個id屬性:

type Foo = {
  id: string,
  // other props
}

type Bar = {
  id: number,
  // other props
}

現在想象一下React中的Table組件,它接受數據數組作為屬性。 該組件必須是通用的,但是我們知道它為數據數組中的每個數據對象都需要一個id屬性。 id可以是數字或字符串。 道具的類型如下:

type Props = {
  data: Array<{id: number | string}>
}

問題是上述表示法不起作用。 有沒有一種方法可以“重新鍵入”某些屬性?

我已經研究了泛型類型,但是如果不更改FooBar類型定義,我似乎找不到解決方案。

我覺得Flow有點棘手。 因此,不必聲明兩個類型都共享一個屬性,而是可以將數組聲明為包含Foo | Bar type類型Foo | Bar Foo | Bar

這很好,因為它的重復次數甚至比原始代碼少,並且在if語句的每個分支中,您都可以自由訪問FooBar其他唯一屬性,而不會出現任何問題。

// @flow

type Foo = {
  id: string,
  // other props
}

type Bar = {
  id: number,
  // other props
}

type Props = {
  data: Array<Foo | Bar>
}

const foo: Foo = { id: 'A' }
const bar: Bar = { id: 1 }
const props: Props = { data: [foo, bar] }

for (const item of props.data) {
  if (typeof item.id === 'string') {
    console.log('I am a Foo')
  } else {
    console.log('I am a Bar')
  }
}

嘗試Flow Link

暫無
暫無

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

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