Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. // install @types/react-redux and other nonsense
  2.  
  3. import * as React from 'react'
  4. import { connect } from 'react-redux'
  5. import { YourActualAppState } from './wherever-it-is.ts'
  6.  
  7. export function mapStateToProps({
  8. whatever
  9. }: YourActualAppState) {
  10. return {
  11. whateverStateField: WhateverStateFieldType
  12. }
  13. }
  14.  
  15. export function mapDispatchToProps(dispatch: Function) { // or whatever for dispatch, I don't care here
  16. return {
  17. whateverDispatchField: (whatever: WhateverDispatchArgType) => dispatch(whatnot(whatever)) // if you try to use Ramda compose here, your types will be fucked, probably
  18. }
  19. }
  20.  
  21. const ExtractStateProps = (false as true) && mapStateToProps({} as any) // trick compiler into evaluating return value, maybe this will be a feature in 2.5+
  22. type StateProps = typeof ExtractStateProps
  23.  
  24. const ExtractDispatchProps = (false as true) && mapDispatchToProps({} as any) // again
  25. type DispatchProps = typeof DispatchProps
  26.  
  27. export type Props = { // actual props your component needs from parent
  28. whateverPropField: WhateverPropType
  29. }
  30.  
  31. type Clean<T> = Pick<T, keyof T> // Clean/Pick trick suggested by @gcanti for cleaner intersections
  32. type Type = Clean<Props & StateProps & DispatchProps> // intersection type for your component
  33. // OR
  34. type Type = Props & StateProps & DispatchProps // intersection type for your component
  35. /* Type is now basically this:
  36. {
  37. whateverPropField: WhateverPropType
  38. whateverStateField: WhateverStateFieldType
  39. whateverDispatchField: (whatever: WhateverDispatchArgType) => any
  40. }
  41. */
  42.  
  43. export YourComponent: React.ComponentClass<Props> = connect( // important: set Props for exporting the type
  44. mapStateToProps,
  45. mapDispatchToProps
  46. )(function (props: Type) { // important: Type here for your intersection type
  47. return (
  48. <YourJSXSoup />
  49. )
  50. })
  51.  
  52. // congrats, now you have something actually useful that type checks in your whole app, unlike most every example I've seen
  53. // remember: if you value your sanity, choose any compile-to-JS language that isn't Javascript/Typescript/Flow
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement