Skip to content

Instantly share code, notes, and snippets.

@justinwoo
Last active November 15, 2017 22:45
Show Gist options
  • Save justinwoo/c55a133c38974ed49c3861cb22d89ade to your computer and use it in GitHub Desktop.
Save justinwoo/c55a133c38974ed49c3861cb22d89ade to your computer and use it in GitHub Desktop.
// install @types/react-redux and other nonsense
import * as React from 'react'
import { connect } from 'react-redux'
import { YourActualAppState } from './wherever-it-is.ts'
export function mapStateToProps({
whatever
}: YourActualAppState) {
return {
whateverStateField: WhateverStateFieldType
}
}
export function mapDispatchToProps(dispatch: Function) { // or whatever for dispatch, I don't care here
return {
whateverDispatchField: (whatever: WhateverDispatchArgType) => dispatch(whatnot(whatever)) // if you try to use Ramda compose here, your types will be fucked, probably
}
}
const ExtractStateProps = (false as true) && mapStateToProps({} as any) // trick compiler into evaluating return value, maybe this will be a feature in 2.5+
type StateProps = typeof ExtractStateProps
const ExtractDispatchProps = (false as true) && mapDispatchToProps({} as any) // again
type DispatchProps = typeof DispatchProps
export type Props = { // actual props your component needs from parent
whateverPropField: WhateverPropType
}
type Clean<T> = Pick<T, keyof T> // Clean/Pick trick suggested by @gcanti for cleaner intersections
type Type = Clean<Props & StateProps & DispatchProps> // intersection type for your component
// OR
type Type = Props & StateProps & DispatchProps // intersection type for your component
/* Type is now basically this:
{
whateverPropField: WhateverPropType
whateverStateField: WhateverStateFieldType
whateverDispatchField: (whatever: WhateverDispatchArgType) => any
}
*/
export YourComponent: React.ComponentClass<Props> = connect( // important: set Props for exporting the type
mapStateToProps,
mapDispatchToProps
)(function (props: Type) { // important: Type here for your intersection type
return (
<YourJSXSoup />
)
})
// congrats, now you have something actually useful that type checks in your whole app, unlike most every example I've seen
// remember: if you value your sanity, choose any compile-to-JS language that isn't Javascript/Typescript/Flow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment