facebook / flow

Adds static typing to JavaScript to improve developer productivity and code quality.
https://flow.org/
MIT License
22.09k stars 1.86k forks source link

should treat React `static defaultProps` a non-null value #4010

Closed xareelee closed 7 years ago

xareelee commented 7 years ago

We already provide a default value if the props don't have this value, but flow still treats it as an optional type.

// Developing a React Native app
const deviceScreen = Dimensions.get('window');

class Foo extends React.Component {

  props: {
    offset?: number
  };

  // We provide a non-null default value for props if it is `undefined`.
  static defaultProps = {
    offset: deviceScreen.width * 0.75,
  }

  animate = () => {
  // We already provide a default value if the props don't have this value, but flow still treats it as an optional type.
  const value = this.props.offset - 70;  
  //            ^^^^^^^^^^^^^^^^^ undefined. The operand of an arithmetic operation must be a number.
  }

  // ...
}
agentcooper commented 7 years ago

Check docs section about this.

"Note: You don’t have to mark your defaultProps as optional properties in your props. Flow knows how to handle them properly.".

xareelee commented 7 years ago

@agentcooper thanks for the info. I missed it.

BTW, IMOH, I think flow should correct this issue if there is a default value for the optional type, doesn't it?

Developers might only check the type of the props to use a React component. If a prop is optional, the developer knows that he/she won't have to pass a value to the component.