Skip to content

How to use type transformResponse with enhanceEndpoints in TS.  #2244

Open
@mattduggan

Description

@mattduggan

I'm using the Typescript RTK Query code gen plugin to generate some api hooks.

Example:

const injectedRtkApi = api.injectEndpoints({
  overrideExisting: true,
  endpoints: (build) => ({
    Notification: build.query<NotificationQuery, NotificationQueryVariables>({
      query: (variables) => ({ document: NotificationDocument, variables })
    }),
  }),
});

export { injectedRtkApi as api };
export const { useNotificationQuery, useLazyNotificationQuery } = injectedRtkApi;

I'd like to use enhanceEndpoints to return one of the nested values in the query result:

import {
    api, NotificationQuery,
} from './Notification.generated';

export const {useNotificationQuery} = api.enhanceEndpoints({
    endpoints: {
        Notification: {
            transformResponse: (result: NotificationQuery) => result.notificationByNotificationId
    }
}});

When I do this, TypeScript throws the following error, which I interpret as it expecting transformResponse to be undefined:

TS2322: Type '(result: NotificationQuery) => { __typename?: "Notification" | undefined; id: string; }' is not assignable to type 'undefined'.

I also tried using the definition:

export const {useNotificationQuery} = api.enhanceEndpoints({
    endpoints: {
        Notification(definition) {
            definition.transformResponse: (result: NotificationQuery) => result.notificationByNotificationId
    }
}});

Which is happier but suggests that NotificationQuery['notificationByNotificationId'] is not assignable to NotificationQuery.

Where I use the hook, it also still thinks that data is NotificationQuery and not NotificationQuery['notificationByNotificationId'].

This has my head scratching as there aren't any examples I could find of overriding the ResultType.

I'm using TypeScript 4.4.4 and RTK 1.8.1.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions