1

Similar to Using a forwardRef component with children in TypeScript but I am looking for an example where the referenced object is also generic like react-native FlashList or FlatList

I got it to work like this

export const DragFlashList = forwardRef<FlashList<any>, DragFlashListProps<any>>((props, ref) => <DragListImpl {...props} ref={ref} />);

but I want to get rid of the any

or this doesn't work

export function DragFlashList<T>  {
    return forwardRef<FlashList<T>, DragFlashListProps<T>>((props, ref) => <DragListImpl {...props} ref={ref} />);
}

But I want it to use arrow functions.

The technique I did What is the syntax for Typescript arrow functions with generics? doesn't appear to do work correctly because forwardRef builds the function. The following isn't valid typescript

export const DragFlashList = <T,>forwardRef<FlashList<T>, DragFlashListProps<T>>((props, ref) => <DragListImpl {...props} ref={ref} />);

1 Answer 1

-1

try:

export const forwardRefGeneric = <P, R>(fc: (props: P, ref: ForwardedRef<R>) => JSX.Element) => {
    return forwardRef(fc) as unknown as (props: P & { ref: ForwardedRef<R> }) => JSX.Element;
}

usage:

export function DragFlashList<T>() {
    return forwardRefGeneric<FlashList<T>, DragFlashListProps<T>>((props, ref) => <DragListImpl {...props} ref={ref} />);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.