Last active
November 7, 2021 01:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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