1
votes

I'm trying to implement flow into my React application. So far it worked fine, but i'm having trouble with a default value.

The function header is:

const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (

The type alias for TFormControls is:

type TFormControls = {
  onSubmit?: boolean,
  onReset?: boolean,
  onClear?: boolean
}

I would expect, since I put a maybe operator in there controls: ?TFormControls, that it would either be my type-alias or null/undefined, but flow tells me:

src/components/forms/FormControls.jsx:35
 35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
                                   ^^^^^^^^ null. This type is incompatible with
 35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
                                   ^^^^^^^^ object type

src/components/forms/FormControls.jsx:35
 35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
                                   ^^^^^^^^ object type. This type is incompatible with
 35: const FormControls = ({ form, controls = null, labels = {} }: { form: any, controls: ?TFormControls, labels?: TFormControlLabels}) => (
                                   ^^^^^^^^ null

Any pointers would be most welcome!

Edit: As requested, the full function with error as an example

1
Can you post a complete example? It would make it easier for the people who are trying to help you. You can even just post a link to what you come up with in flowtype.org/try - Nat Mote

1 Answers

3
votes

What you're looking for is the defaultProps class property.

In particular, here is how you might define your prop parameters:

type FormControlsPropsType = {
  form: Object,
  controls: TFormControls,
  labels: TFormControlLabels
};

const FormControls = ({
  form,
  controls,
  labels
} : FormControlsPropsType): React.Element<*> => (
  // ...etc
);

And here is how you might define defaultProps:

FormControls.defaultProps = {
  controls: null,
  labels: {},
}

Finally, because you are defining defaults there is no reason to define the PropsType with optional parameters. You'll see I removed the ?'s.

By setting defaults in the parameter definitions, you may have been running into conflicts with React$Element internals.

Here is a working FlowType example.