What type should props have in functional HOC in TS?

235 Views Asked by At

I write functional HOC to add query in component. HOC must accept functional and classes components.

I write this code:

const LISTS_QUERY = gql`
    query List {
        list {
            id
            address
            name
        }
    }
`;
interface WithListQueryProps {
    listQueryResult: QueryResult<ListQuery>;
}
type WithList =
    <T extends WithListProps, S extends {}>(Component: React.FC<T> | React.ComponentClass<T, S>)
        => (props: any)
            => JSX.Element;
export const withList: WithList = (Component) => {
    return props => (
        <Query<ListQuery>
            query={LISTS_QUERY}
        >
            {listQueryResult => (
                <Component
                    {...props}
                    listQueryResult={listQueryResult}
                />
            )}
        </Query>
    );
};

This HOC called so:

interface Props {
    userName: string;
}

export const MenuConnect: React.FC<Props> = (props: Props) => {
    const MenuBehaviourWithList = withList(MenuBehaviour);
    return (
        <MenuBehaviourWithList {...props}/>
    );
};

HOC worked. I don't like any. Need change type props in type WithList in HOC from any to your.

1

There are 1 best solutions below

0
SailorStat On

Write type inside function. Swap call to imperative.


export const withList = <P extends WithListProps, S extends {}>(
    Component: React.FC<P> | React.ComponentClass<P, S>,
) => {
    return (props: React.PropsWithChildren<Omit<P, 'listQueryResult'>>): JSX.Element => (
        <Query<GetListQuery, GetListQueryVariables> query={LIST_QUERY} >
            {listQueryResult => (
                React.createElement(Component, { ...props, listQueryResult } as P)
            )}
        </Query>
    );
};