Search code examples
typescriptreduxredux-toolkit

Redux Toolkit Query and TypeScript: How to implement transformResponse


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?


Solution

  • 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)
            }
        }),
    ...