Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify optional prop types in flow?

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.

like image 611
Robert Balicki Avatar asked May 26 '17 17:05

Robert Balicki


People also ask

How do you pass optional props in React?

To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.

Can we assign value to props?

You would change the prop in the parent component, as that is what holds the value of the prop itself. This would force a re-render of any child components that use the specific prop being changed.

Are PropTypes deprecated?

PropTypes is deprecated since React 15.5. 0, use the npm module prop-types instead .


1 Answers

You can specify optional props by putting a ? after the property name. For example

type Props = {
  optionalString?: string,
  maybeString: ?string,
}

I can omit optionalString, but if I pass it, it must be a string or undefined. maybeString I must pass, but it's value can be null, undefined, or a string.

You can play with it in an example here

The docs talk about optional object properties here.

like image 120
TLadd Avatar answered Nov 22 '22 15:11

TLadd