Reputation: 1362
Given the following code using PropTypes (see this issue)
const SomeComponent = ({comp}) => {...}
SomeComponent.propTypes = {
comp: PropTypes.shape({
type: PropTypes.oneOf([SomeOtherComponent])
})
}
what is the equivalent using Flow types?
I've only gotten as far as:
const SomeComponent = ({comp}: {comp: React$Element<any>}) => {...}
using this for reference, but that will allow comp
to be any React component.
How do I type-check a prop to ensure it is an instance of a specific React component using Flow?
Upvotes: 4
Views: 498
Reputation: 1362
As of Flow 0.53, this can be done using React.Element<typeof Component>
.
Upvotes: 0
Reputation: 10532
Short answer: You can't. React elements are created at runtime, and Flow can only use data which can be obtained through its own static analysis, which is not powerful enough to determine the component class which will be used to create a React element at runtime. This is complicated mostly because the component class used to create an element could be defined only at runtime. Allowing Flow to try to determine the runtime type of an element would inevitably make it run into situations where it would be perfectly valid to use the component you want, but Flow wouldn't allow you.
If you want to check the type of a component prop, do it at runtime as explained in this question. You can disable this kind of check in production by having a global variable indicating "development mode". For instance:
function elementIsOfType(element, typeName) {
if (!__DEV__) {
return true;
}
return element.type.displayName === typeName;
}
You could then set the __DEV__
variable to false
to disable all runtime checks.
Upvotes: 2