使用Typescript泛型和react-apollo查询组件

时间:2019-06-22 22:15:44

标签: reactjs typescript apollo react-apollo

我正在尝试包装查询组件,以便在返回错误时显示错误消息。为了正确使用Typescript,我的新组件需要使用类似于react-apollo中的Query组件的泛型。当我尝试传递包装程序接受的泛型时,出现以下错误。

Type '{ 
    children: (props: QueryResult<TData, TVariables>) => Element; query: any; 
    displayName?: string | undefined; skip?: boolean | undefined; 
    onCompleted?: ((data: TData) => void) | undefined; ... 9 more ...; 
    partialRefetch?: boolean | undefined; 
}' 
is not assignable to type 
'Pick<InferProps<{ 
    client: Requireable<object>; 
    children: Validator<(...args: any[]) => any>; 
    fetchPolicy: Requireable<string>; 
    notifyOnNetworkStatusChange: Requireable<boolean>; 
    onCompleted: Requireable<...>; ... 5 more ...; 
    partialRefetch: Requireable<...>; 
}>, Exclude<...> | ... 9 more ... | Exclude<...>>'.

下面是包装程序的代码。有人可以帮助我了解如何正确使用泛型并摆脱此错误。

import React from "react";
import ErrorMessage from "../components/ErrorMessage";
import { Query, QueryProps, QueryResult } from "react-apollo";

/**
 * This component can be used to to display error messages when a query
 * or mutation returns an error.  To do so, simply wrap a component
 * using the function dipslayError(Component) and use that instead of the
 * Query or Mutation component.
 *
 * Additionally, a function errorToMessage can be passed as a prop to the wrapped component.
 * This function will be ran on the returned error to convert the error into a message.  If
 * the function is not provided, the message displayed will be error.message.
 *
 */

export interface QueryWithErrorProps<TData, TVariables> extends QueryProps<TData, TVariables> {
    errorToMessage?: (error: Error) => string;
}

const QueryWithError = <TData, TVariables>(props: QueryWithErrorProps<TData, TVariables>) => {
    const { children, errorToMessage, ...rest } = props;
    let getMessage: (error: Error) => string;
    if (errorToMessage) getMessage = errorToMessage;
    else {
        getMessage = error => {
            return error.message;
        };
    }
    return (
        <Query<TData, TVariables> {...rest}>
            {(props: QueryResult<TData, TVariables>) => {
                const { error } = props;
                return (
                    <React.Fragment>
                        {children(props)}
                        {error && <ErrorMessage message={getMessage(error)} />}
                    </React.Fragment>
                );
            }}
        </Query>
    );
};
QueryWithError.displayName = "QueryWithError";
export default QueryWithError;

Picture of error

0 个答案:

没有答案