reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.64k stars 1.15k forks source link

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

Open kasper-se opened 2 years ago

kasper-se commented 2 years ago

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)
phryneas commented 2 years ago

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.

msutkowski commented 2 years ago

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.

kasper-se commented 2 years ago

@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.

jessecoleman commented 2 years ago

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.