Last active
August 23, 2020 19:44
-
-
Save rosskevin/6c103846237ecbc77862ea0f3218187d to your computer and use it in GitHub Desktop.
Typescript higher order component (hoc) template
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
/* variation on https://medium.com/@DanHomola/react-higher-order-components-in-typescript-made-simple-6f9b55691af1 */ | |
import * as React from 'react' | |
import { wrapDisplayName } from 'recompose' | |
// Props you want the resulting component to take (besides the props of the wrapped component) | |
interface ExternalProps {} | |
// Props the HOC adds to the wrapped component | |
export interface InjectedProps {} | |
// Options for the HOC factory that are not dependent on props values | |
interface Options { | |
key?: string | |
} | |
const hoc = ({ key = 'Default value' }: Options = {}) => <OriginalProps extends {}>( | |
Component: React.ComponentType<OriginalProps & InjectedProps>, | |
) => { | |
class HOC extends React.Component<OriginalProps & ExternalProps> { | |
render() { | |
return <div /> | |
} | |
} | |
if (process.env.NODE_ENV !== 'production') { | |
(HOC as any).displayName = wrapDisplayName(Component, 'hoc') | |
} | |
return HOC | |
} | |
export default hoc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks!
btw, this fails when you set "declaration: true" on tsconfig.
I've updated the gist using the answer from https://stackoverflow.com/questions/41499831/type-annotation-for-react-higher-order-component-using-typescript
Here's the updated version: https://gist.github.com/devdoomari3/2d330c9c75e2e3c235906173850e0537