Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active August 15, 2023 06:43
Show Gist options
  • Save OliverJAsh/d2f462b03b3e6c24f5588ca7915d010e to your computer and use it in GitHub Desktop.
Save OliverJAsh/d2f462b03b3e6c24f5588ca7915d010e to your computer and use it in GitHub Desktop.
TypeScript React HOC using `forwardRef`
import * as React from 'react';
import { Component, ComponentClass, createRef, forwardRef, Ref } from 'react';
const myHoc = <ComposedComponentProps extends {}>(
ComposedComponent: ComponentClass<ComposedComponentProps>,
) => {
type ComposedComponentInstance = InstanceType<typeof ComposedComponent>;
type WrapperComponentProps = ComposedComponentProps & {
wrapperComponentProp: number;
};
type WrapperComponentPropsWithForwardedRef = WrapperComponentProps & {
forwardedRef: Ref<ComposedComponentInstance>;
};
class WrapperComponent extends Component<
WrapperComponentPropsWithForwardedRef,
{}
> {
render() {
const {
forwardedRef,
wrapperComponentProp,
...composedComponentProps
} = this.props;
return (
<ComposedComponent
ref={forwardedRef}
// We need a cast because:
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/32355
// https://github.com/Microsoft/TypeScript/issues/28938#issuecomment-450636046
{...composedComponentProps as ComposedComponentProps}
/>
);
}
}
return forwardRef<ComposedComponentInstance, WrapperComponentProps>(
(props, ref) => <WrapperComponent forwardedRef={ref} {...props} />,
);
};
type MyComponentProps = { composedComponentProp: number };
class MyComponent extends Component<MyComponentProps> {}
const ref = createRef<MyComponent>();
const badRef = createRef<ComponentClass<{}>>();
const MyComponentAfterHoc = myHoc(MyComponent);
//
// Tests
//
// should succeed:
<MyComponentAfterHoc composedComponentProp={1} wrapperComponentProp={1} />;
<MyComponentAfterHoc
composedComponentProp={1}
wrapperComponentProp={1}
ref={e => {}}
/>;
<MyComponentAfterHoc
composedComponentProp={1}
wrapperComponentProp={1}
ref={ref}
/>;
// should error:
<MyComponentAfterHoc
composedComponentProp={1}
wrapperComponentProp={1}
ref={badRef}
/>;
<MyComponentAfterHoc composedComponentProp={'1'} wrapperComponentProp={1} />;
<MyComponentAfterHoc composedComponentProp={'1'} wrapperComponentProp={'1'} />;
<MyComponentAfterHoc />;
@HughParsons
Copy link

I ended up using decomposing the ref and prop types from ForwardRefExoticComponent, see my gist.

It let me wrap the HOC multiple times and errored on badRefs, although not the most extensively tested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment