typescriptaxios

Property 'data' does not exist on type 'Awaited<R>'.(2339)


The generic parameters of the request function are same with 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 expect that the TS type of response should be AxiosResponse, but the actual type is Awaited<R>. I also expect the type of response.data should be T(AxiosResponse['data']).

TS Playground


Solution

  • The type parameter R is only defaulted to AxiosResponse<T>. If you call json with a different type in that position, then there might not be a data member.

    The type parameter R extends AxiosResponse<T> = AxiosResponse<T> would be more appropriate.

    Playground link