Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flowtype: conditionally required type

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?

like image 287
Yan Takushevich Avatar asked Apr 09 '26 17:04

Yan Takushevich


1 Answers

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).

like image 68
Nat Mote Avatar answered Apr 12 '26 10:04

Nat Mote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!