Reputation: 5421
I would like to declare that my react-redux mapStateToProps
function is returning correctly-typed properties and not omitting any.
If I do it this way, it complains about dispatch in props. If I made it not $Exact
, I think it wouldn't catch missing or extra props.
I was thinking that myComponent could declare a static field with type Props so I could read off the type from there, but that seems like a hack and I would need to do it for every component.
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);
src/myComponent/myComponent.js
type Props = {
myKey: string,
}
export default class MyComponent extends React.Component {
props: Props;
...
}
Upvotes: 3
Views: 1659
Reputation: 10532
I think you shouldn't use $Exact
with props. It is not an error in React to specify extra props, and a lot of libraries depend on this behavior. If you use the Props
type without $Exact
, it will still catch missing props ("In JavaScript, accessing a property that doesn’t exist evaluates to undefined. This is a common source of errors in JavaScript programs, so Flow turns these into type errors."), but won't complain about extra props being passed (in fact, the behavior of object types in Flow was changed to allow for objects with extra fields not specified in the type)
Of course, the ideal solution here would be for Flow to allow object types to be extended, for instance:
type Props = { /* ... */ }
type ReduxProps = { ...Props, dispatch: /* ... */ }
but while this feature doesn't land, I believe it's just best to tolerate extra props to be passed. It should be reasonably safe, too, as Flow won't let you read from unknown props iirc.
Upvotes: 1