流类型:可扩展的React Component prop类型

问题描述 投票:0回答:1

假设存在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 [1]中缺少属性CustomOptionType,但在属性OptionType的第一个参数中存在于onPressItem [2]中。

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

javascript reactjs flowtype
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.