Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active Nov 7, 2021
Embed
What would you like to do?
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