Using TypeScript with axios and encountering an undefined property

Currently, I am encountering an issue while attempting to type the axios response. Here is a glimpse of how the response type appears:

export interface GetBreedsResponse {
  data: {
    message: Breed[]
  }
}

Within my router file, I have implemented the following code:

router.get("/breeds", async (_req: Request, res: Response) => {
  try {
    const apiResponse = await axios.get<GetBreedsResponse>("https://url");
    let breeds : Breed  = await apiResponse.data.message;
    // some code
  }catch (err: unknown) {
    // some code
  }
});

An error occurs indicating that the property message does not exist on GetBreedsResponse. It seems to be related to the fact that message is nested inside the data property, but I am uncertain about how to resolve this.

Answer ā„–1

RetrieveBreedsResponse is intended to outline the structure of the body in the HTTP response.

The data attribute does not form part of the response body; rather, it is where axios stores the response body.

export interface RetrieveBreedsResponse {
    message: Breed[]
  }
}

TJ highlights that there is an attempt to assign message (Breed[] - an array) to breeds (Breed - not an array), resulting in mismatched types.

Answer ā„–2

There are a couple of key points to consider:

  1. It seems like there's a mismatch between using breeds: Breed and the type of message, which is actually Breed[] (an array). Based on the plural form, it appears that you may have intended to use Breed[].
  2. When specifying the type argument for axios.get (and similar methods), the type refers to the data property within the returned AxiosResponse. Therefore, you should define the desired type as follows:
export interface GetBreedsResponse {
    message: Breed[];
}

By doing this, you won't need to explicitly annotate the type for breeds since it will automatically be inferred as Breed[]:

export interface GetBreedsResponse {
    message: Breed[];
}

router.get("/breeds", async (_req: Request, res: Response) => {
    try {
        const apiResponse = await axios.get<GetBreedsResponse>("https://url");
        let breeds = await apiResponse.data.message;
        // your code logic here
    } catch (err: unknown) {
        // error handling logic here
    }
});

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

Output a .twig file using Twig.js

I'm trying to use Twig.js to render a template and save the generated HTML into a file, but I can't seem to find any information about it in the documentation. Issue twig = require('twig'); ... _prevTicket = function(req, res){ ...

The name 'XXX' is nowhere to be found

I encountered an error stating "Cannot find name 'Calendar Component'" while attempting to add a route to a component from another module in my app.module.ts file. Below is the content of my app.module.ts file: // Importing Modules // import {B ...

Creating dynamic Angular child routes with variable initial segment

Recently, I've been working on a new project to set up a blogging system. The next step in my plan is to focus on the admin section, specifically editing posts. My idea for organizing the routes is as follows: /blog - Home page /blog/:slug - Access ...

Retrieving the name of the currently active express middleware function

Greetings to all! I have been an avid reader for a long time, but this is my first time reaching out with a question. My inquiry pertains to dynamically accessing function names in Express ^4.17.1. Despite thorough research on both the internet and the exp ...

When Mongo Meets Express

I have been exploring the concept of related data in MongoDB, where I have one collection for users and another for posts. The posts collection contains a field called created_by, which is a reference to the users collection. However, I am facing difficu ...

Unable to retrieve notes(data) from API using the user ID

I am trying to retrieve notes data from an API using user_id, but I am encountering difficulties in making the API call. Despite my attempts to log the error, I am unable to fetch the required data. Can someone assist me in identifying what might be miss ...

Can you determine the base class type based on the derived class?

I've encountered a typings issue while working on a new feature for my TypeScript library. Let's dive into the problem with the following example: class Base { ... } class User extends Base { ... } class Product extends Base { ... } class Comp ...

Developing a Liferay 7.0 portlet using Angular and TypeScript

Is it possible to develop a Liferay 7.0 portlet using Angular (2, Angular Material v1.1.1) and TypeScript? I am aware that it is possible to incorporate Angular 1.4 library and create a portlet using plain JavaScript/Angular code, as mentioned in this sou ...

Countdown component in Ant Design failing to display correct date

Iā€™m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Extract an array from a JSON array based on the lowest value of the keys

Consider the following array: [{ "activity" : "Hiking", "level" : "8.5" }, { "activity" : "Swimming", "level" : "-3.2" }] I want to loop through the JSON data and identify the object with the lowest value for level. In this example, I sho ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

What is preventing the availability of those array extensions during runtime?

Looking for a simple way to work with arrays, I decided to create this custom extension class: export class ArrayType<T extends IEntity> extends Array<T> { add(item: T) { this.push(item); } remove(item: T) { console.log(item); ...

Angular: use an icon in place of text

Consider this scenario where a component.ts file looks like the following: @Input() studentHeader?: BaseStudent; get studentText() { if(this.studentHeader) { return this.studentHeader.nr + ' - ' + this.studen ...

What is the correct way to configure the environment variables for the vscode plugin?

After attempting to set it using cross-env, the variable remained undefined following execution in VSCode. What steps can I take to resolve this issue? https://i.sstatic.net/bKYLe.png ...

The middleware in ExpressJs does not seem to function properly following its import

Below is the code snippet from my app.js file: import path from 'path'; import bodyParser from 'body-parser'; import express from 'express'; import defender from 'inflex-defend-api'; import { key, secret } from &a ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...

Displaying an ejs file on the client's side

Struggling to implement AJAX functionality for cloning an 'item' template. I am attempting to insert an EJS template containing information about the newly cloned item into the main EJS page after each POST request. However, I am having difficult ...

Sequelize error: the defineCall method is not found in the Index.js file

Recently, I've encountered this perplexing sequelize error /node_modules/sequelize/lib/sequelize.js:508 this.importCache[path] = defineCall(this, DataTypes); ^ TypeError: defineCall is not a function at module ...

Is there a beginner's pack or trial version available for utilizing TypeScript with IBM Cloud Functions / OpenWhisk?

While working on developing actions in IBM Cloud Functions, I have been primarily using Node.js / Javascript and Python for coding. However, I haven't come across specific instructions on how to incorporate TypeScript into IBM Cloud Functions. I am c ...

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...