How do I specify optional prop types in flow?

Viewed 7970

I'd like to declare a component in an external library definition (I'm writing flow types for react-bootstrap) so that I have optional and required props, and no extra props. I have the following:

declare export type AlertProps = {|
  bsClass: bsClass,
  bsStyle: ?bsStyle,
  onDismiss: ?(e: SyntheticEvent) => any,
  closeLabel: ?string,
  style: ?style,
|}

declare export class Alert extends React$Component {
  props: AlertProps;
}

(For the sake of this example, lets assume bsStyle is actually required.) However, flow still complains if I omit bsClass

49:     props: AlertProps;
               ^^^^^^^^^^ property `bsClass`. Property not found in
26:       ? (<Alert bsStyle="danger" style={{ textAlign: 'center' }}>
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ props of React element `Alert`. See: src/components/audit/AuditAlert.jsx:26

If I wrap my props in $Shape<>, I cannot have required props. A workaround I have is as follows:

declare export type AlertProps = {
  // required props go here
  bsClass: bsClass,
} & $Shape<{|
  // all props (optional and required) go here
  bsClass: bsClass,
  bsStyle: bsStyle,
  onDismiss: (e: SyntheticEvent) => any,
  closeLabel: string,
  style: style,
|}>

However, this seems excessively hacky! Is there a better way to achieve my goal?

As a side note, this question is not answered correctly.

1 Answers
Related