As a flow type props when using a reaction-reduction connection

I would like to declare that my react-redux function mapStateToProps

returns correctly printed properties and does not skip any.

If I do that, it complains about sending in props. If I didn't $Exact

, I think it won't catch missing or extra props.

I thought myComponent could declare a static field with a props type so that I can read the type from there, but this seems like a hack and I will need to do this for each component.

In src/mycomponent/index.js

:

import {connect} from 'react-redux'
import type {Props} from './myComponent';
import MyComponent from './myComponent'

function mapStateToProps(state: State): $Exact<Props> {
  return {
    myKey: state.myKey,
  };
}

export default connect(mapStateToProps)(MyComponent);

      

IN src/myComponent/myComponent.js

type Props = {
  myKey: string,
}

export default class MyComponent extends React.Component {
   props: Props;
   ...
} 

      

+3


source to share


1 answer


I guess you shouldn't use $Exact

with props. It is not a mistake in React to specify additional props, and many libraries depend on this behavior. If you use a type Props

without $Exact

, it will still catch missing props ( In JavaScript, accessing an object that does not exist evaluates to undefined.This is a common source of errors in JavaScript programs, so Flow turns them into type errors. ) But won't complain about passing additional props (in fact, the behavior of object types in the stream has been changed to allow objects with additional fields not specified in the type)

Of course, the ideal solution here would be for Flow to allow extending object types, for example:



type Props = { /* ... */ }
type ReduxProps = { ...Props, dispatch: /* ... */ }

      

but until this feature lands I find it best to endure additional props to go through. It should also be secure enough as Flow will not let you read unknown iirc props.

0


source







All Articles