[英]Flow type: extendable React Component prop types
Let say there exist the SelectOption component, which props looks like: 假设存在SelectOption组件,其道具如下所示:
type OptionType = {
+id: string,
+label: string,
}
type Props = {|
+options: OptionType[],
+onItemPress: OptionType => void
|}
Intentionally I wrote the OptionType type as a not exact because I expect that I will need to extend this type, but I expected that id and label are always required. 我故意将OptionType类型写为不完全是因为我希望我需要扩展该类型,但是我希望始终需要id和label。
But this doesn't work as I expected. 但是,这不符合我的预期。
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`.
)
}
}
With this approach I have this error: 用这种方法,我有这个错误:
Cannot create
Select
element because propertylocationId
is missing inCustomOptionType
[1] but exists inOptionType
[2] in the first argument of propertyonPressItem
. 无法创建Select
,因为属性元素locationId
中缺少CustomOptionType
[1],但在存在OptionType
物业的第一个参数[2]onPressItem
。
How should I wrote props that have some required fields(id, label), but with possibility extend the OptionType? 我该如何编写具有某些必填字段(id,标签)但有可能扩展OptionType的道具?
I changed the OptionType to Interface which solved my issue. 我将OptionType更改为Interface,这解决了我的问题。 https://flow.org/en/docs/types/interfaces/ https://flow.org/en/docs/types/interfaces/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.