Skip to content

Instantly share code, notes, and snippets.

@mikebridge
Created May 4, 2017 22:30
Show Gist options
  • Save mikebridge/9abd8407a6f022c8f9d213d15c1c0426 to your computer and use it in GitHub Desktop.
Save mikebridge/9abd8407a6f022c8f9d213d15c1c0426 to your computer and use it in GitHub Desktop.
A TypeScript HOC to inject props into a component from Redux
import * as React from "react";
import * as ReactRedux from "react-redux";
export interface IWithPersonalizationProps {
name: string;
}
type HOC<PWrapped, PHoc> = React.ComponentClass<PWrapped & PHoc> | React.SFC<PWrapped & PHoc>;
export function withPersonalization<P, S>(Component: HOC<P, IWithPersonalizationProps>): React.ComponentClass<P> {
class C extends React.Component<P & IWithPersonalizationProps, S> {
public render(): JSX.Element {
console.log(this.props);
// Without "as any", this gives me the error:
// "error TS2700: Rest types may only be created from object types."
// I think this is related to
// https://github.com/Microsoft/TypeScript/issues/12756#issuecomment-265812676
const {name, ...rest} = this.props as any;
return (
<Component name={this.props.name} {...rest} />
);
}
}
const mapStateToProps = (state: any, ownProps: P): IWithPersonalizationProps => ({
name: state.user.name
});
return ReactRedux.connect(mapStateToProps)(C);
}
export default withPersonalization;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment