【发布时间】:2019-10-05 14:39:52
【问题描述】:
我正在尝试编写 HOC 以在组件中显示已用查询的信息,如下所示:
const GET_RATES = gql`
query ratesQuery {
rates(currency: "USD") {
currency
rate
}
}
`;
class RatesQuery extends Query<{
rates: { currency: string; rate: string }[];
}> {}
const RatesQueryWithInfo = withQueryInfo(RatesQuery);
const Rates = () => (
<RatesQueryWithInfo query={GET_RATES}>
{({ loading, error, data }) => {
if (loading) return "Loading...";
if (error || !data) return "Error!";
return (
<div>
{data.rates.map(rate => (
<div key={rate.currency}>
{rate.currency}: {rate.rate}
</div>
))}
</div>
);
}}
</RatesQueryWithInfo>
);
withQueryInfo 看起来像(它的实现是基于article):
const withVerbose = <P extends object>(
WrappedComponent: React.ComponentType<P>
) =>
class extends React.Component<P> {
render() {
return (
<div>
{(this.props as any).query.loc.source.body}
<WrappedComponent {...this.props as P} />;
</div>
);
}
};
这个 HOC 工作正常(它在上面的原始组件中附加查询字符串)但是打字被破坏了
withQueryInfo(RatesQuery) 中的错误
Argument of type 'typeof RatesQuery' is not assignable to parameter of type 'ComponentType<QueryProps<{ rates: { currency: string; rate: string; }[]; }, OperationVariables>>'.
Type 'typeof RatesQuery' is not assignable to type 'ComponentClass<QueryProps<{ rates: { currency: string; rate: string; }[]; }, OperationVariables>, any>'.
Types of property 'propTypes' are incompatible.
Type '{ client: Requireable<object>; children: Validator<(...args: any[]) => any>; fetchPolicy: Requireable<string>; notifyOnNetworkStatusChange: Requireable<boolean>; onCompleted: Requireable<(...args: any[]) => any>; ... 5 more ...; partialRefetch: Requireable<...>; }' is not assignable to type 'WeakValidationMap<QueryProps<{ rates: { currency: string; rate: string; }[]; }, OperationVariables>>'.
Types of property 'fetchPolicy' are incompatible.
Type 'Requireable<string>' is not assignable to type 'Validator<"cache-first" | "cache-and-network" | "network-only" | "cache-only" | "no-cache" | "standby" | null | undefined>'.
Types of property '[nominalTypeHack]' are incompatible.
Type 'string | null | undefined' is not assignable to type '"cache-first" | "cache-and-network" | "network-only" | "cache-only" | "no-cache" | "standby" | null | undefined'.
Type 'string' is not assignable to type '"cache-first" | "cache-and-network" | "network-only" | "cache-only" | "no-cache" | "standby" | null | undefined'.ts(2345)
而且{ loading, error, data } 也隐含了一个“任意”类型。
此示例的 CodeSanbox 是 here。
如何为这个 HOC 编写合适的类型?
【问题讨论】:
-
我不确定最初的错误,但您可以通过 a.) 从 react-apollo 导入 {QueryResult} 为查询结果提供 QueryResult 类型。 B.) 声明类型如下:({loading, data, error}:QueryResult)
-
@MichaelKnight 是的,这只是部分解决方案,但在使用
QueryResult时不会输入data。我的目标是在包装在 HOC 中时不要触摸原始RatesQueryWithInfo。
标签: reactjs typescript apollo react-apollo