Use React-redux Connect In Typescript
Solution 1:
A couple of things I notice:
1) As far as I've seen in examples and when working with props
in TypeScript, your call to React.Component
needs to specify Props
as a type argument like so:
exportdefaultclassTestPageextendsReact.Component<Test.Props, Test.State>{
constructor(props: Test.Props) {
super(props);
}
}
You can specify that your component does not accept props
or state
by passing empty interfaces i.e.:
exportdefaultclassTestPageextendsReact.Component<{}, {}>{
// constructor becomes 'useless' at this point and is not neededconstructor() {
super();
}
}
I think this explains why your call signature is not matching and why there are no properties visible on this.props
- TS sees an interface of ReadOnly{}
since it has no type arguments passed in.
2) Your mapStateToProps
function doesn't look quite right. mapStateToProps
takes two arguments, state
(referencing your Redux store
) and ownProps
as an optional second argument, which refers to props
passed down from the parent. So mapStateToProps
should look like this:
function mapStateToProps(state: any, ownProps: { label: string }) {
return {
label: ownProps.label
};
}
This is my guess for why connect
is throwing an error - it is simply a place where you make assertions about how Redux should handle combining props
coming from the store
and props
coming from the parent. Let me know if this works out.
Solution 2:
This doesn't work because connect is a generic function. This means you need to provide additional type parameters.
connect<StateProps, DispatchProps>({
mapStateToProps,
mapDispatchToProps,
})(SomeComponent);
You can find typing implementation here. Everything you need to know is there C:
Solution 3:
Working syntax variant for Type Script application is:
import * asReactfrom'react';
import { connect } from'react-redux';
interfaceComponentProps {
// Your properties here
}
interfaceComponentState {
// Your properties here
}
interfaceMapStateToPropsTypes {
// Your properties here
}
interfaceMapDispatchToPropsTypes {
// Your properties here
}
classMyComponentNameextendsReact.Component<ComponentProps, ComponentState> {
constructor(props: ComponentProps) {
super(props);
}
}
exportdefault connect<MapStateToPropsTypes, MapDispatchToPropsTypes>(
mapStateToProps,
mapDispatchToProps)
(MyComponentName)
Post a Comment for "Use React-redux Connect In Typescript"