I am trying to create a generic component where a user can pass the a custom OptionType
to the component to get type checking all the way through. This componen
Creating a generic component as output of React.forwardRef
is not directly possible1 (see bottom for further info). There are some alternatives though - let's simplify your example a bit for illustration:
type Option<O = unknown> = {
value: O;
label: string;
}
type Props<T extends Option<unknown>> = { options: T[] }
const options = [
{ value: 1, label: "la1", flag: true },
{ value: 2, label: "la2", flag: false }
] // just some options data
// Given input comp for React.forwardRef
const FRefInputComp = <T extends Option>(props: Props<T>, ref: Ref<HTMLDivElement>) =>
<div ref={ref}> {props.options.map(o => <p>{o.label}</p>)} </div>
// Cast the output
const FRefOutputComp1 = React.forwardRef(FRefInputComp) as
<T extends Option>(p: Props<T> & { ref?: Ref<HTMLDivElement> }) => ReactElement
const Usage11 = () => <FRefOutputComp1 options={options} ref={myRef} />
// options has type { value: number; label: string; flag: boolean; }[]
// , so we have made FRefOutputComp generic!
This works, as the return type of forwardRef
in principle is a plain function. We just need a generic function type shape. You could an extra type to make the assertion simpler:
type ForwardRefFn<R> = <P = {}>(p: P & React.RefAttributes<R>) => ReactElement | null
// RefAttributes is built-in with ref and key props defined
const Comp12 = React.forwardRef(FRefInputComp) as ForwardRefFn<HTMLDivElement>
const Usage12 = () => <Comp12 options={options} ref={myRef} />
const FRefOutputComp2 = React.forwardRef(FRefInputComp)
// T is replaced by its constraint Option<unknown> in FRefOutputComp2
export const Wrapper = <T extends Option>({myRef, ...rest}:
Props<T> & {myRef: React.Ref<HTMLDivElement>}) => <FRefOutputComp2 {...rest} ref={myRef} />
const Usage2 = () => <Wrapper options={options} myRef={myRef} />
This one is my favorite - simplest alternative, a legitimate way in React and doesn't use forwardRef
.
const Comp3 = <T extends Option>(props: Props<T> & { myRef: Ref<HTMLDivElement> }) =>
<div ref={myRef}> {props.options.map(o => <p>{o.label}</p>)} </div>
const Usage3 = () => <Comp3 options={options} myRef={myRef} />
1 The type declaration of React.forwardRef
is:
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ...
So it takes a generic component-like interface, whose type parameters T, P must be concrete. In other words: ForwardRefRenderFunction
is not a generic function declaration, so higher order function type inference cannot propagate free type parameters on to the calling function React.forwardRef
.
Playground