流类型:可扩展的React Component道具类型

时间:2019-02-25 13:07:49

标签: javascript reactjs flowtype

假设存在SelectOption组件,其道具看起来像:

type OptionType = {
 +id: string,
 +label: string,
}

type Props = {|
  +options: OptionType[],
  +onItemPress: OptionType => void
|}

我故意将OptionType类型写为不完全是因为我希望我需要扩展该类型, 但我希望始终需要id和label。

但是这不符合我的预期。

type CustomOptionType = {
  +id: string,
  +label: string,
  +locationId: string,
}

const customOption = [
 {
 id: 'id',
 label: "label",
 locationId: 'ID-location'
 }
]


class PlacePicker extends React.Component<{}> {

  handleItemClick = (option: CustomOptionType) => {
    // 
  }

  render() {

    const mockedCustomOption = [
     {
       id: 'id',
       label: "label",
       locationId: 'ID-location'
     }
    ]

    return(
      <Select options={mockedCustomOption} onPressItem={this.handleItemClick} />
      // Cannot create `Select` element because property `locationId` is missing in `CustomOptionType` [1] but exists in `OptionType` [2] in the first argument of property `onPressItem`.
      )
    }
}

使用这种方法,我会遇到以下错误:

  

无法创建Select元素,因为属性locationId为   在CustomOptionType [1]中丢失,但在OptionType [2]中存在   属性onPressItem的第一个参数。

我应该如何编写具有某些必填字段(id,标签)但有可能扩展OptionType的道具?

1 个答案:

答案 0 :(得分:0)

我将OptionType更改为Interface,这解决了我的问题。 https://flow.org/en/docs/types/interfaces/

相关问题