Redux Toolkit Query和TypeScript:如何实现transformResponse

huangapple go评论103阅读模式
英文:

Redux Toolkit Query and TypeScript: How to implement transformResponse

问题

编译器试图告诉您什么:

编译器在这里试图告诉您,您的 transformResponse 函数的返回类型与 Redux Toolkit Query 期望的类型不匹配。具体来说,编译器指出以下问题:

  1. 您的 transformResponse 函数返回类型为 Posts[],但 Redux Toolkit Query 期望它返回类型为 PostsResponse[]Promise<PostsResponse[]>

  2. 您的 Posts 类型缺少了 PostsResponse 类型的一些属性,包括 idcreatedupdatedversion 等属性。

因此,编译器在类型检查过程中发现了这些不匹配,导致了错误消息的产生。要解决这个问题,您需要确保 transformResponse 函数返回的类型与您的 Redux Toolkit Query 预期的类型相匹配,并且 Posts 类型包含了 PostsResponse 类型的所有属性。

英文:

I am using Redux Toolkit Query and I am trying to implement transformResponse

...
    getPosts: builder.query&lt;PostsResponse[], void&gt;({
        query: () =&gt; GET_POSTS,                       
        transformResponse: (response: PostsResponse[], meta, arg): Posts[] =&gt; {
            return converPostsForUi(response)
        }
    }),
...

However, I am getting:

Type &#39;Posts[]&#39; is not assignable to type &#39;PostsResponse[] | Promise&lt;PostsResponse[]&gt;&#39;. &#160;&#160;&#160;&#160;
Type &#39;Posts[]&#39; is not assignable to type &#39;PostsResponse[]&#39;. 
Type &#39;Posts&#39; is missing the following properties from type &#39;PostsResponse&#39;: id, created, updated, version, and 4 more.  
endpointDefinitions.d.ts(53, 5): The expected type comes from property &#39;transformResponse&#39; which is declared here on type &#39;Omit&lt;EndpointDefinitionWithQuery&lt;void, BaseQueryFn&lt;string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta&gt;, PostsResponse[]&gt; &amp; { ...; } &amp; { ...; } &amp; QueryExtraOptions&lt;...&gt;, &quot;type&quot;&gt; | Omit&lt;...&gt;&#39;

What is the compiler trying to tell me?

答案1

得分: 0

builder.query(&lt;RETURNTYPE&gt;, void)中的返回类型更改为transformResponse()函数的返回类型

...
    getPosts: builder.query&lt;Posts[], void&gt;({
                              ^
     此类型必须与transformResponse()中的返回类型匹配
        query: () =&gt; GET_POSTS,                       
        transformResponse: (response: PostsResponse[], meta, arg): Posts[] =&gt; {
            return converPostsForUi(response)
        }
    }),
...
英文:

Change the return type in builder.query(&lt;RETURNTYPE&gt;, void) to the return type of the transformResponse() function

...
    getPosts: builder.query&lt;Posts[], void&gt;({
                              ^
     This type must match the return type in transformResponse()
        query: () =&gt; GET_POSTS,                       
        transformResponse: (response: PostsResponse[], meta, arg): Posts[] =&gt; {
            return converPostsForUi(response)
        }
    }),
...

huangapple
  • 本文由 发表于 2023年8月10日 14:54:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定