The requested property is not available on the specified type

Here is a code snippet:

import { QueryClient, useQuery, useQueryClient, UseQueryOptions } from "@tanstack/react-query"

export function useQueryFactory(getConfig: (queryClient: QueryClient) => UseQueryOptions) {
    const queryClient = useQueryClient()
    const config = getConfig(queryClient)

    return useQuery(config)
}

class Account {
    static findMany() {
        return {
            async queryFn() {
                return {
                    accounts: [{
                        id: 123
                    }],
                }
            },
            queryKey: ["Country", "findMany"],
        }
    }
}

export function AccountsList() {
    const { isSuccess, data } = useQueryFactory(Account.findMany)

    if (isSuccess) {
        // error here Property 'accounts' does not exist on type 'unknown'
        const { accounts } = data

        console.log(accounts)
    }
}

Can anyone explain why this error occurred and how to fix it?

Playground

Answer №1

The issue you are facing is that the function useQueryFactory() always returns a

UseQueryResult<unknown, Error>
. Regardless of the input passed to it, the output type remains constant. This results in the returned value having a data property of type unknown.

If you desire the return type of useQueryFactory() to vary based on the type of the getConfig argument, you must make the function generic. By examining useQuery(), it seems like altering the call signature as follows will solve the problem:

export function useQueryFactory<T>(
  getConfig: (queryClient: QueryClient) => UseQueryOptions<T>
) {
    const queryClient = useQueryClient()
    const config = getConfig(queryClient)
    return useQuery(config)
}

Notice the introduction of the type parameter T. Consequently, the function's call signature now appears as

/* function useQueryFactory<T>(
     getConfig: (queryClient: QueryClient) => UseQueryOptions<T>
   ): UseQueryResult<T, Error> */

This implies that it yields a UseQueryResult<T>, thereby being dependent on the type of getConfig(). Subsequently, everything falls into place smoothly:

export function AccountsList() {
    const { isSuccess, data } = useQueryFactory(Account.findMany)
    if (isSuccess) {
        const { accounts } = data
        //      ^? const accounts: { id: number; }[]
        console.log(accounts)
    }
}

Follow this link for a demo.

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

Organize by a collection of strings or a collection of enums

Here is a list of objects that I have: enum MealType { Breakfast, Lunch, Dinner } interface FoodItem { name: string, type: MealType[], } const foodItems: FoodItem[] = [ { name: 'Pizza', type: [MealType.Lunch, MealType.Dinner ...

"Error: In TypeScript, the Child Method is not recognized within the Parent

I'm a newcomer to TypeScript and object-oriented programming. I am attempting to use a method from a child class in the parent class, but for some reason, the method is not being recognized. Below is my Child class: import {Ouvrage} from "./Clas ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

Is there a way for me to verify that the key of one object is a subset of the keys of another object?

export const masterKeysObject = { MAIN: 'main', REDIRECT: 'redirect', DASHBOARD: 'dashboard', USER_ID_PARAM: ':userId', CREATE_NEW: 'create_new' } as const; type MasterKeys = keyof type ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Enhance your Typescript code with a type guard that supports optional wrapped types

I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type. type A = { id: number, title: string, type: stri ...

What is the correct method for using typedef to define a function with the signature "() => void" in accordance with tslint guidelines?

Currently, I am working on a function that requires specific typing: const checkIfTagNeedsToBeCounted = (listOfTags: string[]): boolean => { const tagsToExcludeFromCounting: string[] = [ "DoNotCount", ]; const excludedTagFound: boolean = lis ...

Using TypeScript with React may result in an error message stating that a string cannot be assigned to a parameter of type 'keyof T'

I've encountered an issue with my sorting function that I built using TypeScript and React Hooks. The error message I'm getting is: Argument of type 'string' is not assignable to parameter of type 'keyof T'. Type 'stri ...

Tips for identifying the cause of a memory leak in browser notifications

I am looking to implement browser notifications in a browser extension. However, I have noticed that the memory usage does not decrease after closing the notification. Can someone explain why this may be happening? Allow StackOverflow show notifications i ...

Error in Typescript TS2339: The property 'queryType' is missing in the type 'IntrinsicAttributes' within a Typescript, React, and Redux application

I am currently utilizing TypeScript in my React + Redux application. Within one of my components, I am using the connect function from react-redux. Here is a snippet of the code: import * as React from 'react'; import * as Redux from 'redux ...

VSCode not displaying Typescript errors when using Vue 3 and Volar

Trying to utilize Typescript with Vue 3 in VSCode has been a bit of a challenge for me. Initially, I relied on the Vetur plugin for error highlighting, but it was a bit too eager and not recommended by official Vue 3 documentation. https://i.sstatic.net/ ...

Is it possible to use programming to invoke a function with the identical name from within another function in Javascript or Typescript?

Currently, I am working with Typescript but presenting this question in Javascript. Any assistance for either language would be greatly appreciated. I have two objects that share the same interface. My goal is to create a third object with the same interf ...

We could not locate the export in Typescript, and the JSX element type does not show any construct or call signatures

Looking to utilize my Typescript React Component Library as a Package. The structure of my files is as follows: MyComponent.tsx: import React, { FunctionComponent } from 'react'; import styled from 'styled-components'; export interf ...

TypeOrm throws an error: ColumnTypeUndefinedError - the column type for #name is unspecified and cannot be inferred

An error occurred while trying to decorate the target with decorator: ^ ColumnTypeUndefinedError: The column type for Author#name is not defined and cannot be guessed. To fix this issue, make sure to enable "emitDecoratorMetadata" option in tsconfig.j ...

What is the best way to set a boolean value for a checkbox in a React project with Typescript?

Currently, I am working on a project involving a to-do list and I am facing an issue with assigning a boolean value to my checkbox. After array mapping my to-dos, the checkbox object displays 'on' when it is unchecked and a 'Synthetic Base E ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...

Deactivate the Mention and Hash tag in ngx-linkifyjs

I am currently utilizing ngx-linkifyjs to automatically convert URLs in text to clickable hyperlinks. However, I am facing an issue where it is also converting # and @ tags into links. Is there a way to prevent the conversion of # and @ while maintain ...

Issue: Module '@nrwl/workspace/src/utilities/perf-logging' not found

I attempted to run an Angular project using nxMonorepo and made sure to install all the necessary node modules. However, when I tried running the command "nx migrate --run-migrations" in my directory PS C:\Users\Dell\Desktop\MEANAPP&bso ...

Tips for creating a mapped type in TypeScript that is based on an array

Is there a way to create a function with dynamic properties? function magic(...propertyNames:string[]): { ????? : any } { .... } Could the returned type have properties listed in propertyName? For instance: type ResultType = {alpha:any, bravo:any}; le ...

A Project built with React and TypeScript that includes code written in JavaScript file

Is it an issue when building a React project with Typescript that includes only a few JS components when moving to production? ...