typescript - 创建突变后添加到 Apollo 客户端缓存中的数组
问题描述
在通过突变创建项目后,尝试将项目自动添加到 Apollo 客户端中的缓存数组中,第 32 行(data: {
)出现 TypeScript 错误:
Type '{ [x: string]: TFetchResultData[]; }' is not assignable to type 'TQuery'.
'{ [x: string]: TFetchResultData[]; }' is assignable to the constraint of type 'TQuery', but 'TQuery' could be instantiated with a different subtype of constraint 'Record<string, TFetchResultData[]>'.ts(2322)
DataProxy.d.ts(17, 9): The expected type comes from property 'data' which is declared here on type 'WriteQueryOptions<TQuery, TVariables>'
这是完整的代码
import { ApolloCache, DataProxy } from '@apollo/client'
export const addToArray = <
TVariables,
TData,
TFetchResultData,
TQuery extends Record<string, TFetchResultData[]>,
K
>(
cache: ApolloCache<K>,
{
query,
variables,
fieldName,
newItem,
}: {
query: DataProxy.Query<TVariables, TData>['query']
variables: DataProxy.Query<TVariables, TData>['variables']
newItem: TFetchResultData
fieldName: keyof TQuery
}
): void => {
// Add to the documentFiles field, if it exists
const queryResult = cache.readQuery<TQuery, TVariables>({
query,
variables,
})
if (queryResult) {
cache.writeQuery<TQuery, TVariables>({
query,
variables,
data: {
[fieldName]: [...queryResult[fieldName], newItem],
},
})
}
}
解决方案
Typescript 抱怨TQuery
可能有其他字段会被您的代码剥离。
添加...queryResult
到您的writeQuery
代码中:
cache.writeQuery<TQuery, TVariables>({
query,
variables,
data: {
...queryResult,
[fieldName]: [...queryResult[fieldName], newItem],
},
})
推荐阅读
- javascript - 在 wordpress 中运行多个 js 脚本
- c# - .Net Core API - 混合模型绑定不起作用
- google-bigquery - 基于两列删除除大查询标准sql中最新出现的所有重复项
- arrays - Swift过滤器对象数组和另一个对象数组
- mathjax - MathML 标签:“stretchy”属性问题
- javascript - 在 .forEach 循环中使用变量名
- perl - Perl 系统 Grep 和粘贴
- javascript - 在函数结束时检查执行错误的代码?
- html - 如何在特定条件下隐藏点击(Angular 4+)?
- sql - 在多列中前向填充 NULL 值