question:
I need to use an High Order Component that can infer type for FlatList with typescript.
<CustomFlatList<MyObject>
// props
/>
How can I do without errors?
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.
// my code so far
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
/>
<CustomFlatList<MyObject> // Expected 0 type arguments, but got 1
// 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 FlatList
export class FlatList<ItemT = any> extends React.Component<FlatListProps<ItemT>>
// My buggy code
export 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.