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.
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.
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.
PropTypes is deprecated since React 15.5. 0, use the npm module prop-types instead .
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.
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