I have the following code in my React app:
import isRequiredIf from 'react-proptype-conditional-require'
Auth.propTypes = {
children: PropTypes.any,
step: PropTypes.number,
steps: isRequiredIf(PropTypes.number, props => props.hasOwnProperty('step')),
footer: PropTypes.any
}
Here steps is required only if step is specified.
I'm migrating my React PropTypes to Flow. Can I somehow achieve the same behavior with Flow?
This can't be done with Flow in this form. Since PropTypes are checked at runtime, and not statically, there can be more flexibility. If a static typechecker allowed this sort of thing, it would be undecidable.
However, you could do something like this:
type Props = {
children: any,
// not sure about this name, but you get the idea
step: ?{
step: number,
steps: number,
},
footer: any,
}
Or, if you can have steps but not step:
type Props = {
children: any,
// not sure about this name, but you get the idea
step: ?{
step?: number,
steps: number,
},
footer: any,
}
Obviously, neither of these options is quite as concise as what you have, and it will require changing the code that produces and consumes these values. Unfortunately there is sometimes a price to be paid in order to gain the safety of a static typechecker.
Another option is to just leave them both optional:
type Props = {
children: any,
step?: number,
steps?: number,
footer: any,
}
This way, Flow won't enforce that steps exists if step exists. However, you won't have to change your other code, and there's nothing stopping you from adding a runtime check (which will be no worse than what you already have).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With