Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement