I want to enhance the redux connect feature by using it as a decorator for a specific reducer/state. Although I know that redux connect can already be used as a decorator, I am curious about why my custom implementation does not work the way I expect.
Here is the Higher Order Component (HOC) that I am currently using as a decorator:
interface InjectedProps { userId: string; }
type ComponentType<P> = React.ComponentClass<P> | React.StatelessComponent<P>;
type StateToProps = (setting: ApplicationState) => InjectedProps;
export function withUserSetting(
stateToProps?: StateToProps
): <P extends InjectedProps>(WrappedComponent: ComponentType<P>) => void {
return <P extends InjectedProps>(Comp: ComponentType<P>) => {
class NewComponent extends (Component || PureComponent)<P> {
render() {
return <Comp {...this.props} />;
}
}
return connect(stateToProps)(NewComponent as any);
};
}
This HOC works fine and alerts me if the Props are missing because it expects the return type of 'InjectedProps':
https://i.stack.imgur.com/q5K4r.gif
However, I would like to modify the HOC so that it can alert me based on the return type of the 'stateToProps' function:
type AnyFunction = (...args: any[]) => any;
type ComponentType<P> = React.ComponentClass<P> | React.StatelessComponent<P>;
type StateToProps = (setting: ApplicationState) => { [key: string]: any };
export function withUserSetting<T extends AnyFunction>(
stateToProps?: StateToProps
): <P extends ReturnType<T>>(WrappedComponent: ComponentType<P>) => void {
return <P extends ReturnType<T>>(Comp: ComponentType<P>) => {
class NewComponent extends (Component || PureComponent)<P> {
render() {
return <Comp {...this.props} />;
}
}
return connect(stateToProps)(NewComponent as any);
};
}
As you can see, the 'InjectedProps' is no longer required, allowing for flexibility in choosing prop names. Additionally, I am assuming that the 'ReturnType' decorator will automatically recognize the props and alert me if they are not declared for the component. However, it does not seem to have any effect:
https://i.stack.imgur.com/nAzb1.gif
The decorator itself works fine, but I am still missing the type safety that I desire. Do you have any ideas on why it is not working?