51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Redux Toolkit Query和TypeScript:如何实现transformResponse

英文:

Redux Toolkit Query and TypeScript: How to implement transformResponse

问题 {#heading}

编译器试图告诉您什么:

编译器在这里试图告诉您,您的 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 {#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)
        }
    }),
...

赞(0)
未经允许不得转载:工具盒子 » Redux Toolkit Query和TypeScript:如何实现transformResponse