To begin, you should establish an interface that encapsulates the entire state of the application:
interface ApplicationState {
someProp1: {
someProp1a: string;
someProp1b: number;
};
someProp2: {
someProp1a: string;
someProp1b: number;
};
}
Subsequently, create individual interfaces to represent the state of each smart component (which is a component connected to the store through mapStateToProps
):
interface SomeComponentState {
someProp1: {
someProp1a: string;
someProp1b: number;
};
}
The MyComponentState
interface needs to be a subset of AppState
, allowing for this type of definition:
type SomeComponentProps = Pick<ApplicationState, "someProp1">;
Furthermore, define a type to represent the actions specific to the smart component:
const actionsCreators = {
doSomething: (txt: string) => ({ type: "DO_SOMETHING", payload: txt })
};
type SomeComponentActions = { actions: typeof actionsCreators };
The properties of the smart component consist of both its properties and its actions, combined into
SomeComponentProps & SomeComponentActions
.
class MyComponent extends React.Component<SomeComponentProps & SomeComponentActions, void> {
public render() {
return <div onClick={() => this.props.actions.doSomething(this.props.someProp1.someProp1a)} >Click me!</div>;
}
}
You will need to map from the application state to the component state:
function mapStateToProps(state: ApplicationState): SomeComponentProps {
return {
someProp1: state.someProp1
};
}
function mapDispatchToProps(dispatch: Redux.Dispatch<typeof actionsCreators>) {
return { actions : bindActionCreators(actionsCreators, dispatch) };
}
const MySmarthComponent = connect(mapStateToProps, mapDispatchToProps)(MyComponent);