How do I use React $ Element in FlowType?
Here is my simple component <ListItem />
. I want it to have a token that only allows two types of components to be used: <Icon />
or <Label />
.
import React, { Element } from 'react';
import { Icon } from '../Icon';
import { Label } from '../Label';
type Props = {
marker?: Element<Icon> | Element<Label>,
};
const ListItem = ({ marker }: Props) => {
return (
<div>{marker}</div>
);
};
export default ListItem;
How can I present a simple use case in FlowType? I tried the following, but they all don't seem to work. This is why I am wondering how to properly use React $ Element to accurately resolve two specific types of react components?
type Marker = Icon | Label;
type Props = {
marker?: Element<Marker>,
};
type Props = {
marker?: Element<Icon> | Element<Label>,
};
source to share
A pattern that you are trying to work in versions Flow version 0.53.0 and later, with a slight change: the type parameter Element
is the type of expressions such as, but Icon
and Label
are values. You should use typeof
to designate their types:
type Props = {
marker?: Element<typeof Icon> | Element<typeof Label>,
};
The stream type definitions for React have changed significantly in v0.53.0, including a change that toggled the type parameter Element
from Config
to React$ElementType
, making it much easier to talk about elements created by specific components.
Hack for Flow v0.52.0 and earlier
@Lewis Chung pointed out in a comment that the Config
before- Element
before-stream v0.53.0 parameter is generated by an expression $Diff<Props, DefaultProps>
. If Icon
u Label
have different types of props, you can distinguish elements created by these components in older versions of Flow using a hack like this:
type Props = {
marker?: Element<IconProps> | Element<LabelProps>,
};
It is assumed that Icon
they Label
do not have default requisites. If they do, you need to expand that type to get the appropriate differences:
type Props = {
marker?:
| Element<$Diff<IconProps, IconDefaultProps>>
| Element<$Diff<LabelProps, LabelDefaultProps>>,
};
source to share