The 'data' property cannot be found on the 'Awaited<R>' type, according to error code 2339

The parameters for the request function are the same as those in the axios.request() method.

import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

async function request<T = any, R = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<R> {
    const r = await axios.request<T, R>(config);
    return r;
}

async function json<T = any, R = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<T> {
    const response = await request<T, R>(config);
    return response.data;  // TSC throws error here
}

I expected the TS type of response to be AxiosResponse, but it actually is Awaited<R>. I also anticipated the type of response.data to be T(AxiosResponse['data']).

TS Playground

Answer №1

By default, the type parameter R is set to AxiosResponse<T>. If you use a different type when calling json, there may not be a data property.

It would be more suitable to define the type parameter as

R extends AxiosResponse<T> = AxiosResponse<T>
.

Access Playground

Answer №2

UPDATE: @Caleth's response directly tackles the issue at hand.

Below is a streamlined version of your code that effectively resolves the problem:

import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

async function callApi<T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    const result = axios.request<T, AxiosResponse<T>>(config);
    return result;
}

async function fetchJson<T>(config: AxiosRequestConfig): Promise<T> {
    const responseData = await callApi<T>(config);
    return responseData.data;
}

Try it out on TS Playground

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

Key is absent in Typescript generic constraint

I am in the process of developing a series of functions that interact with a generic T type, which is required to adhere to the IDocument interface. While this approach seems promising initially, it appears that TypeScript fails to acknowledge that T shoul ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

Create a TypeScript arrow function and set it as the return value

Looking to create a TypeScript Declaration for ReactMeteorData.jsx, which consists of the following exporting functionality: export default function connect(options) { let expandedOptions = options; if (typeof options === 'function') { e ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Tips for obtaining a file in its raw binary format

One of the challenges I'm facing is dealing with a file upload using antdUpload The HTML code snippet for the uploader is as follows: <Upload beforeUpload={((file: RcFile, fileList: RcFile[]): boolean => {this.requestUpload(file, ( ...

How to retrieve the value of a dynamically added textbox using Angular

While working with input elements in Angular, I noticed that they did not automatically come with a value property or any other properties unless manually added. Even after setting the value property manually, it would not update accordingly. Attempting to ...

Can the Vue instance be accessed in Axios interceptors?

I've integrated vue-reactive-storage to have a reactive alternative to localStorage in my Vue application. This plugin creates a vue object that is accessible to all components. I'm facing an issue when trying to access this object within my axio ...

A guide on how to navigate to a customizable element in React Native

After creating a glossary, I needed a way to access the content of a specific letter by clicking on that letter from a list displayed at the top of my page. However, I encountered an issue - while I managed to implement scrolling functionality, I couldn&ap ...

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Incorporating a Script into Your NextJS Project using Typescript

I've been trying to insert a script from GameChanger () and they provided me with this code: <!-- Place this div wherever you want the widget to be displayed --> <div id="gc-scoreboard-widget-umpl"></div> <!-- Insert th ...

The RxJS race function comes to a standstill if neither stream completes

Consider the code snippet below: import { interval, race, Subject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; const a$ = new Subject<number>(); const b$ = interval(1000).pipe(mapTo(1)); race([a$, b$]).subscribe(consol ...

What is the proper way to utilize queries in BlitzJS?

I am attempting to extract data from a table by filtering based on the relationship with the Blitzjs framework. However, I am facing difficulties using queries as it seems to be the only option available. Every time I try to call the quer ...

Utilizing Angular 4: Sharing Data through Services and Components

After transitioning my data from an object in a service to a database connection, I'm facing issues where the data is not reaching the component as expected. To solve this problem, I have set up the service to subscribe to the data retrieved from the ...

Issue encountered with the inability to successfully subscribe to the LoggedIn Observable

After successfully logging in using a service in Angular, I am encountering an error while trying to hide the signin and signup links. The error message can be seen in this screenshot: https://i.stack.imgur.com/WcRYm.png Below is my service code snippet: ...

Error Message: Unable to access 'map' property of undefined in TSX file

Component for displaying attendees in an activity interface IProps { attendees: IAttendee[] } export const ActivityListItemAttendees: React.FC<IProps> = ({attendees}) => { return ( <List horizontal> {attendees.ma ...

Steps for exporting a package that has been imported

If in file1, the code is like this: import * as Things1 from "../things1" import * as Things2 from "../things2" export { Things1, Things2, } and in file2, it looks like this: import * as Distributor from "../file1" i ...

"Enhance your Vue.js application with the powerful capabilities of vue3-easy

I am currently working on a Vue.js project utilizing the "vue3-easy-data-table" library and following the style recommendations outlined on this particular webpage: Despite attempting to apply the following CSS properties: --easy-table-body-even-row-font ...

Parsing error encountered while trying to handle an unexpected token at line 214, character 33. It appears that an appropriate loader is missing to process this particular file type

I've been developing a Typescript React project for the past few months without any issues. However, things took a turn yesterday when I decided to run npm audit fix and npm audit fix --force in order to address some security concerns that appeared ou ...