Property ‘data’ does not exist on type ‘promise>’

When you see the error message “property ‘data’ does not exist on type ‘Promise>'”, it means that you are trying to access the ‘data’ property on a Promise object, but the TypeScript compiler is not recognizing this property on the Promise type.

This error occurs when you are using Axios to make an HTTP request and expecting a response with data. The problem is that the ‘data’ property is not present on the Promise type itself, but rather on the AxiosResponse object that is resolved by the Promise.

To fix this error, you need to handle the Promise resolution correctly and access the ‘data’ property on the resolved AxiosResponse object. Here’s an example:


import axios, { AxiosResponse } from 'axios';

async function fetchData() {
  try {
    const response: AxiosResponse = await axios.get('https://example.com/api/data');
    const data = response.data;
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData();

In this example, we are using the ‘axios’ library to make an HTTP GET request to ‘https://example.com/api/data’. The result of the request is a Promise, which we are awaiting using the ‘await’ keyword to get the resolved AxiosResponse object. Then, we can access the ‘data’ property on this object.

By specifying the type of ‘response’ variable as ‘AxiosResponse’, TypeScript understands that the resolved value will have a ‘data’ property. This resolves the type error and allows us to safely access the ‘data’ property.

Leave a comment