英文:
Redux Toolkit Query and TypeScript: How to implement transformResponse
问题
编译器试图告诉您什么:
编译器在这里试图告诉您,您的 transformResponse
函数的返回类型与 Redux Toolkit Query 期望的类型不匹配。具体来说,编译器指出以下问题:
-
您的
transformResponse
函数返回类型为Posts[]
,但 Redux Toolkit Query 期望它返回类型为PostsResponse[]
或Promise<PostsResponse[]>
。 -
您的
Posts
类型缺少了PostsResponse
类型的一些属性,包括id
、created
、updated
、version
等属性。
因此,编译器在类型检查过程中发现了这些不匹配,导致了错误消息的产生。要解决这个问题,您需要确保 transformResponse
函数返回的类型与您的 Redux Toolkit Query 预期的类型相匹配,并且 Posts
类型包含了 PostsResponse
类型的所有属性。
英文:
I am using Redux Toolkit Query and I am trying to implement transformResponse
...
getPosts: builder.query<PostsResponse[], void>({
query: () => GET_POSTS,
transformResponse: (response: PostsResponse[], meta, arg): Posts[] => {
return converPostsForUi(response)
}
}),
...
However, I am getting:
Type 'Posts[]' is not assignable to type 'PostsResponse[] | Promise<PostsResponse[]>'.     
Type 'Posts[]' is not assignable to type 'PostsResponse[]'.
Type 'Posts' is missing the following properties from type 'PostsResponse': id, created, updated, version, and 4 more.
endpointDefinitions.d.ts(53, 5): The expected type comes from property 'transformResponse' which is declared here on type 'Omit<EndpointDefinitionWithQuery<void, BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, PostsResponse[]> & { ...; } & { ...; } & QueryExtraOptions<...>, "type"> | Omit<...>'
What is the compiler trying to tell me?
答案1
得分: 0
将builder.query(<RETURNTYPE>, void)
中的返回类型更改为transformResponse()
函数的返回类型
...
getPosts: builder.query<Posts[], void>({
^
此类型必须与transformResponse()中的返回类型匹配
query: () => GET_POSTS,
transformResponse: (response: PostsResponse[], meta, arg): Posts[] => {
return converPostsForUi(response)
}
}),
...
英文:
Change the return type in builder.query(<RETURNTYPE>, void)
to the return type of the transformResponse()
function
...
getPosts: builder.query<Posts[], void>({
^
This type must match the return type in transformResponse()
query: () => GET_POSTS,
transformResponse: (response: PostsResponse[], meta, arg): Posts[] => {
return converPostsForUi(response)
}
}),
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论