Skip to content

Instantly share code, notes, and snippets.

@IniZio
Created January 14, 2022 12:45
Show Gist options
  • Save IniZio/09c91ab89fe5191fba3af63a1c389884 to your computer and use it in GitHub Desktop.
Save IniZio/09c91ab89fe5191fba3af63a1c389884 to your computer and use it in GitHub Desktop.
import { ComponentType } from "react";
type GetProps<C> = C extends ComponentType<infer P> ? P : never;
type Matching<InjectedProps, DecorationTargetProps> = {
[P in keyof DecorationTargetProps]: P extends keyof InjectedProps
? InjectedProps[P] extends DecorationTargetProps[P]
? DecorationTargetProps[P]
: InjectedProps[P]
: DecorationTargetProps[P];
};
const hoc =
<MappedProps, OwnProps>(mapProps: (ownProps: OwnProps) => MappedProps) =>
<C extends ComponentType<Matching<MappedProps, GetProps<C>>>>(
WrappedComponent: C
): ComponentType<
JSX.LibraryManagedAttributes<C, Omit<GetProps<C>, keyof MappedProps>> &
OwnProps
> => {
return (props: any) => {
const newProps = mapProps(props);
return <WrappedComponent {...props} {...newProps} />;
};
};
export default hoc;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment