Flowtype, React and defaultProps

Made in Moon picture Made in Moon · Apr 1, 2018 · Viewed 7.7k times · Source

After hours of searchs and tests, I didn't succeed to find any solution to make flow understand defaultProps

See Try Flow example

Using this model is unconsitent:

type PropsType = {|
  size?: 'small' | 'big',
|};


class Letter extends PureComponent<PropsType> {

  static defaultProps = {
    size: 'small',
  }

}

Thanks

Edit

After Tomasz Mularczyk's suggestion, I created another Try Flow example with:

type PropsType = {|
  size: 'small' | 'big',
|};

instead of

type PropsType = {|
  size?: 'small' | 'big',
|};

But

defaultProp size is not typed anymore:

static defaultProps = {
  size: 'BAD DEFAULT PROPS', // no error (?!)
}

Solution

See Tomasz Mularczyk's answer

+

Don't wait flow error on your current component ( in my case), but where it will be imported and declared.(seems semi-static no?)

Answer

Tomasz Mularczyk picture Tomasz Mularczyk · Apr 1, 2018

Just remove ? from size type. Flow will automatically see that you created defaultProps and will not require it.

From docs:

To type default props add a static defaultProps property to your class.

...

React also supports default props on stateless functional components. Similarly to class components, default props for stateless functional components will work without any extra type annotations.