redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

invalid TypeScript Documentation for usage of transformResponse in rtk-query/enhanceEndpoints

Open kasper-se opened this issue 3 years ago • 4 comments

In the docs, the example says:

// An explicit type must be provided to the raw result that the query returns
// when using `transformResponse`
//                             v
transformResponse: (rawResult: { result: { post: Post } }, meta) => {

But this is not working, as doing so gives me this error (see sandbox example):

Type '(rawResult: { foo: number[]; }, meta: {} | undefined) => number[]' is not assignable to type 'undefined'.ts(2322)

kasper-se avatar Jan 15 '22 21:01 kasper-se

I am pretty sure at this point that that was never possible and is pretty much a documentation bug. rawResult would always be unknown and you'd need to manually cast that.

phryneas avatar Jan 15 '22 22:01 phryneas

I am pretty sure at this point that that was never possible and is pretty much a documentation bug. rawResult would always be unknown and you'd need to manually cast that.

I might be missing something, but this does work.

@kasper-se If you provide the generics on the baseApi definition, this will work as expected. Note: Your return type on the baseApi needs to be the end result type. https://codesandbox.io/s/rtk-query-enhanceendpoints-transformresponse-error-forked-uffd0?file=/src/api.tsx.

If what you're trying to do is let the baseApi return type be inferred and then have the enhanceEndpoint part of transformResponse be your end result type, that isn't possible.

msutkowski avatar Jan 15 '22 23:01 msutkowski

@msutkowski I see! Perhaps that's worth adding to the docs? Because the type errors that occur doesn't really make it clear that I need to have explicit type definitions on the base api.

kasper-se avatar Jan 16 '22 00:01 kasper-se

Does this preclude the usage of transformResponse with codegen tools like @rtk-query/codegen-openapi? It seems like enhanceEndpoints is the only way to intercept the API response types in this case.

jessecoleman avatar Mar 12 '22 19:03 jessecoleman