Define the type of Axios response when making a post request with a body

I am encountering an issue where I need to specify both the JSON body and the response type separately, as they are different. Some examples I've seen have them set to be the same.

Here is the error message I received:

Argument of type '{ grant_type: string; refresh_token: string; }' is not assignable to parameter of type 'AuthResponse'. Object literal may only specify known properties, and 'grant_type' does not exist in type 'AuthResponse'.

This is the response type I defined:

export interface AuthResponse {
  token: string;
  token_type: string;

  access_token: string;
  access_token_expires_at: string;

  refresh_token: string;
  refresh_token_expires_at: string;
}

My use of axios:

axios
      .post<AuthResponse>(
        secrets.authURL,//Defined in enclosing class
        {
          grant_type: this.grantType,//Defined in enclosing class
          refresh_token: this.authPayload,//Defined in enclosing class
        },//<-- Defined as data and conflicts with AuthResponse
        {
          headers: {
            Authorization: this.getAuthHeader(),//Defined in enclosing class
            "Content-Type": this.contentType,///Defined in enclosing class
          },
        }
      )
      .then((axiosResp) => {
        const response = axiosResp.data;//<-- Not the type I'd expect
      });

axiosResp.data is of type

{grant_type: ..., refresh_token: ...}
instead of AuthResponse.

Based on various JavaScript samples, the data should be for the request body, but it seems like it's being incorrectly interpreted as the response type. There might be something fundamentally wrong that I'm doing.

Edit/Answer: As indicated by @jrsharpe's comment, this turns out to be a bug. A fix has been released in v0.23.0 just a few hours ago. This update addresses the bug #4116. Upgrading to version 0.23.0 or higher should resolve the issue.

Answer №1

You have the option to input both in this manner

interface LoginResponse {
    username: string;
    password: string;

    session_token: string;
    session_expires_at: string;

    refresh_token: string;
    refresh_token_expires_at: string;
}

interface Credentials {
    type: string
    secret: string
}

const authenticate = async (): Promise<void> => {

    const response = await axios.post<LoginResponse, AxiosResponse<LoginResponse, Credentials>, Credentials>("theurl", {
        type: 'kjkjk',
        secret: "dddf",
    }, {
        headers: {
            Authorization: "dfdfds",
            "Content-Type": "application/json",
        },
    })

    const result: LoginResponse = response.data

}

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

The method beforeEach in angular2/testing seems to be failing as it is not

Currently, I am utilizing Gulp, Gulp-Jasmine, and SystemJS to conduct tests on an Angular2 demo application. The setup is fairly straightforward. I have successfully implemented a System.config block and loaded the spec file. However, I encounter an error ...

Is it possible for transclusion to display content from external sources using *ngIf and <ng-content>?

In my Angular4 Project, I have come across this snippet of code: <div class="divider"></div> <ng-content select=".nav-toggle"></ng-content> Now, I am trying to figure out a way to display the divider only when there is content pr ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

Safeguarding user data across all components is facilitated by Angular 2

My Angular2 app uses OAuth2 with password grant type for authentication. I currently store the session token on sessionStorage, but I need to securely store additional data such as user roles. While I am aware that sessionStorage or localStorage can be ea ...

Having trouble implementing types with typescript in Vue-toastification for vuejs 3

Having trouble incorporating vue-toast-notification into my vue 3 project. The issue seems to be with vue Augmenting Types. I've tried other solutions without success, encountering the following error: TS2339: Property '$toast' does not exis ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: https://i.sstat ...

Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format. This is my current process: public download(data: any): void { const documentCreator = new D ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

Creating a TypeScript interface for Immutable.js objects: A step-by-step guide

Imagine we are working with the following interface User: interface User { id: number; name: string; bag: Item[]; } Now, let's create a React component: interface UserComponentProps { user: User; } interface UserComponentState {} class Use ...

Encountering an error message stating "Unable to access property 'injector' as null when attempting to downgrade Angular 2 service."

Hello everyone, I could use some assistance with a particular issue I'm facing. Below is the code snippet from my angular 1.x app.js: angular.module('app', []); angular.module('app.test', ['app']) .config(($statePr ...

What is the best way to incorporate a @types module into a TypeScript file that is not already a module?

Setting the Stage: In the process of shifting a hefty ~3,000 line inline <script> from a web-page to a TypeScript file (PageScripts.ts) to be utilized by the page through <script src="PageScripts.js" defer></script>. This script entails ...

Chart.js Axis Labels Orientation Guidelines

I am currently utilizing chart.js within an Angular 8 environment using Primeng. I am looking to customize the options for my chart as follows: For the y-axis ticks, set textDirection to 'ltr' For the x-axis ticks, set textDirection to 'rtl ...

Exploring the functionality of generic components in React Native when using TypeScript

As an illustration, consider export class FlatList<ItemT> extends React.Component<FlatListProps<ItemT>> which incorporates the generic type ItemT. How can I utilize it in a .tsx code? When not parametrized, it appears like this: <Flat ...

Tips for including a dash or hyphen in an input field after two digits in Angular 4

Struggling to format the date of birth input with dashes manually when entered by the user. The desired output should resemble "08-18-2019," but I'm having difficulty achieving this. public dateOfBirth: { year: number; month: number; day: number }; ...

Fresh React framework

I haven't worked on a React app in a while, but when I decided to start a new one and import my old function, I encountered the following error: C:/Users/Hello/Documents/Dev/contacts/client/src/App.tsx TypeScript error in C:/Users/Hello/Documents/Dev ...

What is the best way to reload a React/TypeScript page after submitting a POST request?

I am working on a custom plugin for Backstage that interacts with Argo CD via API calls. To retrieve application information, I make a GET request to the following endpoint: https://argocd.acme.com/api/v1/applications/${app-name} If the synchronizati ...