Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active November 7, 2021 01:06
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/69072c688b7d965cce3deb1eab93cc6d to your computer and use it in GitHub Desktop.
Save tvler/69072c688b7d965cce3deb1eab93cc6d to your computer and use it in GitHub Desktop.
A type-safe high-order-component creator that injects a prop named a given string, with a type inferred by a given hook's return value.
/**
* A type-safe high-order-component creator
* that injects a prop named a given string,
* with a type inferred by a given hook's
* return value.
*
* Ex:
* const Component = ({ name }) => {
* return <>Hello {name}</>;
* };
*
* const withName = hoc('name', () => 'world');
*
* const ComponentWithName = withName(Component);
*
* @param propName The name of the prop to add
* @param usePropValue A hook to return the prop's value
* @returns A high-order-component that injects the given prop
*/
function hoc<PropName extends string, PropType>(
propName: PropName,
usePropValue: () => PropType,
): <Props extends { [key in PropName]: PropType }>(
Component: React.ComponentType<Props>,
) => React.FC<Omit<Props, PropName>> {
return (Component) => (propsWithoutHocProps) => {
const propValue = usePropValue();
const props: React.ComponentProps<typeof Component> = {
...propsWithoutHocProps,
[propName]: propValue,
} as React.ComponentProps<typeof Component>;
return <Component {...props} />;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment