Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6214

Problem with High Order Component using typescript with FlatList

$
0
0

TL; DR

I need to use an High Order Component that can infer type for FlatList.

e.g.

<CustomFlatList<MyObject> // props/>

explanations:

I decided to create a component with custom injected Props into any FlatLists of my app.

I thought an High Order Component was best suited to the situation.

interface InjectedProps {  customProps: any;}export const withCustomProps = <T extends object>(Component: React.ComponentType<T>): React.FC<T & InjectedProps> => ({   customProps,   ...props }: InjectedProps) => {   // a bit of more logic   return <Component {...(props as T)} />; };export const CustomFlatList = withCustomProps(FlatList);

But, not really: everything works fine, excepted with typescript. When I try to strongly type my FlatList in order to infer the other props methods (such as renderItem) I`ve got an error:

<CustomFlatList // works// props/>Expected 0 type arguments, but got 1.ts<CustomFlatList<MyObject> // error// props/>

For now, I have no choice but to use any for the rendering method definition.

renderItem={ ({ item }: { item: any }) => {//whatever} }

I also tried to mimic the syntax of FlatList -- using two nested generic types (T and ItemT)

// React definition of FlatListexport class FlatList<ItemT = any> extends React.Component<FlatListProps<ItemT>>
// My buggy codeexport const withCustomProps = <T extends object, ItemT>(Component: React.ComponentType<T<ItemT>>): React.FC<T & InjectedProps> => ({  customProps,  ...props}: InjectedProps) => {  return <Component {...(props as T)} />;};export const CustomFlatList = withCustomProps(FlatList);

But I've got yet another typescript error:

Type 'T' is not generic.

What can I do better?


Viewing all articles
Browse latest Browse all 6214

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>