A guide on obtaining the ReturnType within a UseQuery declaration

I am currently working on building a TypeScript wrapper for RTKQ queries that can be used generically. I have made progress on most of my goals, but I am encountering an issue with determining the return type for a generic or specific query. I have shared some of the key lines of code from my test below, but if you want to see the complete code, you can check out this code sandbox.

type EndpointKey = keyof typeof api.endpoints;
type Endpoint<EndpointName extends EndpointKey> = typeof injectedAPI.endpoints[EndpointName];
type ReturnQuery<E extends EndpointKey> = Endpoint<E>["useQuery"];

// The return type appears to be Record<string, any> & UseQuerySubscriptionResult<>, but why is the UseQueryStateResult<> missing?
type PuppiesQueryReturnType = ReturnType<ReturnQuery<"getPuppies">>;

const queryReturn: PuppiesQueryReturnType = {} as PuppiesQueryReturnType;
const { data, foo, refetch, isLoading, error } = queryReturn; // All values have type any except for refetch

I'm unsure whether this discrepancy in types is a bug in the RTKQ typings or if I may have missed a step or made an error in my implementation.

Please note that not all of the code provided is originally mine; I have gathered inspiration from various online sources.

Answer №1

Seems like I've found the solution to my issues with the Type TypedUseQueryHookResult from

@reduxjs/toolkit/dist/query/react/buildHooks
. Although it's not mentioned in the documentation, if anyone has a reference, please share it in the comments so I can update accordingly.

By using this, I can achieve something like

type QueryResultInfered<E extends EndpointKey> = Endpoint<E> extends ApiEndpointQuery<
  QueryDefinition<infer QueryArgs, infer BaseQuery, any, infer ResultType>,
  any
>
  ? TypedUseQueryHookResult<ResultType, QueryArgs, BaseQuery>
  : never;

There may be a more straightforward approach without inference, but this should get the job done.

A big thank you to acemarke on the Reactiflux Discord for the assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

What is the best way to assign a default value in mat-select when using an ngFor loop?

Is there a different approach to setting a default value in mat-select within an *ngFor loop? I'm having trouble accessing the element in the array from the loop as desired. .ts file: persons: Person[] = .. //consist of Person with name and age .htm ...

What is the correct way to link an array with ngModel using ngFor loop in Angular?

Utilizing ngModel within an ngFor iteration to extract values from a single input field like this : <mat-card class="hours" > <table id="customers"> <thead > <th >Project</th> ...

Encountering type-checking errors in the root query due to the specific types assigned to my root nodes in a GraphQL and TypeScript application built using Express

As I delve into the world of typescript/graphql, I encountered a peculiar issue while trying to define the type for one of my root nodes. The root node in question simply fetches a user by ID in the resolve function, and thus, I assigned the 'type&apo ...

What is the best way to convert the NextJS router.query.id to a string?

As a newcomer to TypeScript and the T3 stack (React Query / Tanstack Query), I am facing an issue with typing companyId as string. I want to avoid having to type companyId as string every time I use it in my code, but I'm struggling to find the best p ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

Developing with TypeScript, Next.js, and Socket.io

Embarking on a new endeavor utilizing TypeScript, Next.js, and Socket.io has left me puzzled on how to integrate these technologies seamlessly. My project consists of the following files: /api/socket.ts: import { NextApiRequest, NextApiResponse } from &ap ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

How can I pass a ref to a custom component in React with TypeScript using RefForwardingComponent and forwardRef?

I'm attempting to pass a reference to a custom component in order to set focus to that component. However, I am encountering the following error: const RefComp: React.RefForwardingComponent<HTMLInputElement, Props> Type '{ value: string; ...

Encountered difficulty retrieving properties from the req.query object within expressjs

My setup includes a router configuration like this: router.get('/top-5-cheap', aliasTopTours, getAllTours); I've also implemented some middlewares: Middleware aliasTopTours: In this middleware, I am setting certain properties on the reque ...

Sorting through: A producer submerged yielded a fresh outcome *while also* revising its initial version. Opt to yield a fresh outcome *or* revamp the initial version

In my project, I am using an API to retrieve user data from the database. The API response includes two variables - "isActive" and "isVerified". These variables help me determine how to display the data on the interface. If both variables are false, it me ...

Why is my data not showing correctly? - Utilizing Ionic 3 and Firebase

I'm experiencing a challenge with displaying Firebase data in my Ionic 3 application. Below is the relevant snippet of code from my component where 'abcdef' represents a placeholder for a specific user key: var ref = firebase.database().ref ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Angular 8 @viewChild directive resulting in a null value

stripeService.ts @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async initStripeElements() { const elements = this.stripe.elements(); const cardElement = e ...

Retrieve information from Firebase outside of the .on() method

As a newcomer to Typescript, I am struggling to understand how to access the variables latitude1 and latitude2 outside of the this.ref.on('value', (snapshot) function in order to add their values to the locations array. Can anyone provide some gu ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Creating custom components in React

At times, I find myself in need of a special UI component such as a multiple range slider. However, I have a preference for not relying on third-party libraries, so I usually opt to create the component myself. As time has passed, I have completely stopped ...

Issue encountered while implementing a recursive type within a function

I've created a type that recursively extracts indices from nested objects and organizes them into a flat, strongly-typed tuple as shown below: type NestedRecord = Record<string, any> type RecursiveGetIndex< TRecord extends NestedRecord, ...

Encountering an issue with importing a component in a mixin in NuxtJS

Currently, my main technologies are Nuxtjs and Nuxt-property-decorator To prevent repeating a certain method, I created a mixin This method requires the use of a component (Alert component) In order to use the component in the mixin, I imported it Howe ...