Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code:
types:

type SuccessfulResponseData = {
    users: ....
};

interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> {
    status: 200;
}

type FailedResponseData = {
    message: string;
};
interface FailedResponse extends AxiosResponse<FailedResponseData, any> {
   status: 400;
}
export type CustomResponse = SuccessfulResponse | FailedResponse;

Here is an example of how I am implementing it:

const response = await axios
  .post<SuccessfulResponse, AxiosResponse<SuccessfulResponse>>(
    endpoint,
    data,
  )
  .catch((e: AxiosError<FailedResponse>) => {
    return e.response;
  });

return response as CustomResponse;

However, the response does not seem to be compatible with CustomResponse.

Answer №1

Consider using "SuccessResponse" as the response inside a .then function instead of directly after the post.

The ".post" method can either return success or failure, triggering either the ".then" or ".catch" function respectively.

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

Nativescript encountered an error regarding faker: module './address' not found

Currently in the process of learning nativescript, I am experimenting with using faker to generate some data while working with typescript. Here are the versions I am using: Node - 6.9.4 Faker - 3.1.0 Typescript - 2.1.4 Encountered an error which i ...

Dynamic - Swap out middleware during execution

Currently in my Express application, I am looking to switch out a middleware during runtime. Specifically, I want to stop using one middleware (X) and start using another middleware (Y). While I have found a simple solution, it seems like no one else is su ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

Is it Possible to Filter by Individual Properties in Mongo and Node?

I am currently working on a query that involves a criteria object as the first argument: module.exports = (criteria, sortProperty, offset = 0, limit = 20) => { // Implementing sort, offset, and limit options for the query // Criteria is not yet tak ...

NodeJS has a knack for replying even before the function has completed

Struggling with a NodeJS and Express API for a school project. The getAuthUserId function is not working as expected. It decodes the JWT token to retrieve the user Id from the mongoDB server. However, when calling this function in a REST call "/user/authT ...

What methods can be used to get npx to execute a JavaScript cli script on a Windows operating system

The Issue - While my npx scaffolding script runs smoothly on Linux, it encounters difficulties on Windows. I've noticed that many packages run flawlessly on Windows, but the difference in their operations remains elusive to me. Even after consulting A ...

Listening for dates in NodeJS and triggering callbacks

Is there a method or module available that allows me to monitor the date and trigger a specific action when a certain condition is met without relying on setTimeOut? What I am looking for: if(currentHour==="08:00:00"){ doJob() } EDIT : To clarify, wha ...

Exploring creative solutions for generating PDFs with Node JS

Looking for a way to generate PDF Documents in Node.JS? Is there an alternative solution for organizing templates for various types of PDF creation? I've been utilizing PDFKit for creating PDF Documents on the server side with Javascript. Unfortunate ...

The command `node server.js` has been initiated. Nodemon has executed a clean exit and is now waiting for any

A React application has been developed where users can input their email and a message to send to the server. However, upon trying to send the message, Error number 2 is encountered along with viewing Error number 1 in the terminal. Despite ensuring that ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

Exploring the Integration of OverlayScrollbars with TypeScript

Currently, I am delving into TypeScript utilizing a project built on ASP.NET Core 3.0 and the VS 2019 IDE. Recently, I acquired the OverlayScrollbars plugin via npm: . npm install overlayscrollbars npm install @types/overlayscrollbar Provided below is a ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Step-by-step guide on connecting to a MySQL database for Next.js using the .env file

const pool = mysql.createPool({ connectionLimit: 100, host: process.env.NEXT_PUBLIC_MYSQL_HOST, user: process.env.NEXT_PUBLIC_MYSQL_USER, password: process.env.NEXT_PUBLIC_MYSQL_PASSWORD, database: process.env.NEXT_PUBLIC_MYSQL_DATABASE ...

The Next.js API call for /api/contact was successful, but no response was sent back, potentially causing delays in processing other requests

Encountering the issue of API resolved without sending a response for /api/contact, this may result in stalled request on a specific API route within Next.js. Despite successfully sending emails using sendgrid, I am unable to receive a response to handle e ...

Adding Helmet to a Node Server without using Express

As a beginner in the world of npm modules, I am currently experimenting with implementing security headers using the 'helmet' package within a server module. Although 'helmet' is typically used with Express, I am working with a differen ...

Tips for resolving the npm ResourceUnavailable issue

Hey there! I'm currently experimenting with React. In my folder, I've got nodejs along with npm and npx files installed. While debugging, I've deleted and reinstalled this folder multiple times. However, no matter what directory or command I ...

Utilize the Slack API to retrieve data from various components within a message by activating a button click

I have a unique message interface: [ { "type": "section", "text": { "type": "mrkdwn", "text": "Choose the number of items you want to display (Top X)" }, "accessory": { "type": "stat ...

Updating npm globally on a Windows operating system is unsuccessful

I'm really frustrated right now. Whenever I try to execute npm update -g from a regular command prompt, I encounter this issue: npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path C:\Program Files\nodejs\node_modules\.staging ...

Executing multiple parallel async.waterfall functions in Node.js

In my current scenario, I find myself in a situation where I have four Async.waterfall functions that need to be executed simultaneously. Is it viable to accomplish this using Async.parallel or should I look into utilizing a different function? ...