我正在这样设置Apollo Client。
const defaultOptions = {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
mutate: {
errorPolicy: 'all',
},
};
return new ApolloClient({
link: ApolloLink.from([authLink, errorLink, webSocketOrHttpLink]),
defaultOptions, // Typescript don't like this.
queryDeduplication: true,
});
Typescript出现此错误:
Type '{ watchQuery: { fetchPolicy: string; errorPolicy: string; }; query: { fetchPolicy: string; errorPolicy: string; }; mutate: { errorPolicy: string; }; }' is not assignable to type 'DefaultOptions'.ts(2322)
ApolloClient.d.ts(23, 5): The expected type comes from property 'defaultOptions' which is declared here on type 'ApolloClientOptions<NormalizedCacheObject>'
根据文档,this是应该完成的方式。
如何用适当的类型构造defaultOptions
?
答案 0 :(得分:3)
如果您随后检查库的代码,则似乎是问题
//defination of default options
export interface DefaultOptions {
watchQuery?: Partial<WatchQueryOptions>;
query?: Partial<QueryOptions>;
mutate?: Partial<MutationOptions>;
}
//defination of QueryOptions
export interface QueryOptions<TVariables = OperationVariables>
extends QueryBaseOptions<TVariables> {
/**
* Specifies the {@link FetchPolicy} to be used for this query
*/
fetchPolicy?: FetchPolicy;
}
//valid value for FetchPolicy type
export type FetchPolicy =
| 'cache-first'
| 'network-only'
| 'cache-only'
| 'no-cache'
| 'standby';
export type WatchQueryFetchPolicy = FetchPolicy | 'cache-and-network';
因此,对于此处的查询选项,您应该为FetchPolicy
传递任何有效值,而'cache-and-network'
则为无效值。
答案 1 :(得分:0)
2021 年:
如果您尝试使用 cache-and-network
作为 query.fetchPolicy
的默认值:
早在 2019 年,cache-and-network
就不能故意用于 query
的原因在此处进行了解释:
https://github.com/apollographql/apollo-client/issues/3130#issuecomment-478409066
基本上,query()
的行为/逻辑不支持这种策略。因此,他们在打字级别阻止了它。
反应 useQuery() 钩子
如果您使用的是 react,useQuery()
钩子会遵循 watchQuery
而不是 query
的行为。所以配置 watchQuery
就足够了:
import {
ApolloClient,
InMemoryCache,
HttpLink,
DefaultOptions
} from "@apollo/client";
const defaultOptions: DefaultOptions = {
watchQuery: {
fetchPolicy: "cache-and-network",
errorPolicy: "ignore",
notifyOnNetworkStatusChange: true
}
};
export const platformClient = new ApolloClient({
link: new HttpLink({
uri: "https://xxxxx",
credentials: "same-origin"
}),
cache: new InMemoryCache(),
defaultOptions
});