GG.
GG.

Reputation: 21834

Flow: Use the types from connect to deduct the props' types?

Simple example:

const mapStateToProps = (state: State) => ({
  error: state.error, // error: ?string
})

type Props = {
  error: number, // wrong type!
}

class HelloWorld extends Component<Props> { ... }

export default connect(mapStateToProps)(HelloWorld)

My issues:

  1. Not DRY: error comes from the Redux's state and its type is already specified in State
  2. Should be ?string but we can put anything, possibly causing a bug

Is there any way to tell Flow "this prop is coming from the state so take the same type"?

Something like

type Props = PropsFromConnect // { error: ?string }

?

Upvotes: 1

Views: 272

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187004

With some hacking you can get use the return type of a function, and use that as the type of Props.

https://github.com/facebook/flow/issues/4002#issuecomment-344255679


However, I really like to be explicit here. It's very clear and keeps your type errors in the right place if you explicitly type Props and make mapStateToProps return the type Props.

const mapStateToProps = (state: State): Props => ({
  error: state.error, // error: ?string
})

type Props = {
  error: ?string,
}

class HelloWorld extends Component<Props> { ... }

export default connect(mapStateToProps)(HelloWorld)

This way if State's error type changes, then you will get a type error in mapStateToProps because the value no longer conforms to Props. And fixing this is far easier to trying to make sense of inferred types throwing errors in the deep down guts of code where these values are used.

It is less DRY, but the errors it presents when things don't match will be far easier to debug.

Upvotes: 1

Related Questions