A guide to retrieving error response data using axios AsyncThunk typing

I'm struggling to access the error response data. The code worked fine in JavaScript, but since moving to TypeScript, things have gotten confusing. Currently, I'm seeing 'error' is of type 'unknown'.ts(18046)

export const registerClient = createAsyncThunk('clients/register', async (userData: object, { rejectWithValue }) => {
  try {
    const response = await axiosInstance.post('/web/client/register', userData);
    return response.data;
  } catch (error) {
    return rejectWithValue(error.response.data.error);
  }
});

Things I've tried

  • return rejectWithValue((error as any).response.data.error);
    - Getting an Unexpected 'any' error, can't use any type
  • Tried creating a new interface below code - received this error, error' is of type 'unknown'
interface ErrorResponse {
  error: string;
}

const errorResponse: ErrorResponse = error.response.data;
return rejectWithValue(errorResponse.error);

Does anyone have a proper solution for this? Thank you very much

Answer №1

When Typescript is in strict mode, it complains that the error is of an 'unknown' type.

To resolve this issue, you have two options: either set the type to 'any' in catch(error: any) or modify the flag useUnknownInCatchVariables to false in your tsconfig.json file:

"compilerOptions": {
   "useUnknownInCatchVariables": false   
}

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 assignment of Type Observable<Observable<any[]>> to Observable<any[]> is not valid

Working on implementing autocomplete using data from a database service: @Injectable() export class SchoolService { constructor(private db: AngularFirestore) { } getSchools(): Observable<School[]> { return this.db.collection<School> ...

Master the art of properly switching on reducer-style payloads in Typescript

Currently, I am dealing with two types of data: GenArtWorkerMsg and VehicleWorkerMsg. Despite having a unique type property on the payload, my Searcher is unable to differentiate between these data-sets when passed in. How can I make it understand and dis ...

Storing a rendered view in a variable in ExpressJS for handling AJAX responses

I am looking to dynamically load the contents of a partial view (created in Jade) into a Bootstrap modal dialog using an AJAX call. However, I not only need to retrieve the generated HTML but also additional data along with the rendered view. I am hoping t ...

The element is implicitly assigned the 'any' type due to the inability to use an expression of type to index the element

Check out my TS playground here // I have colours const colors = { Red: "Red", Blue: "Blue", Green: "Green" } type TColor = keyof typeof colors; // Some colours have moods associated with them const colorsToMood = { ...

The Node Express proxy is returning a 404 Not Found status code instead of the expected 200 success code

Here is the content of my server.js file: const express = require('express'); const http = require('http'); const path = require('path'); //const request = require('request'); const app = express(); var cors = requi ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

Conceal the Angular Material toolbar (top navigation bar) automatically when scrolling downwards

In my Angular application, the main navigation consists of a standard toolbar positioned at the top of the page. My goal is to have this navigation bar smoothly scroll up with the user as they scroll down, and then reappear when they scroll back up. I at ...

Angular: Real-time monitoring of changes in the attribute value of a modal dialog and applying or removing a class to the element

I cannot seem to figure out a solution for the following issue: I have two sibling div elements. The second one contains a button that triggers a modal dialog with a dark overlay. However, in my case, the first div appears on top of the modal dialog due to ...

Is there a way to conditionally redirect to a specific page using NextAuth?

My website has 2 points of user login: one is through my app and the other is via a link on a third-party site. If a user comes from the third-party site, they should be redirected back to it. The only method I can come up with to distinguish if a user is ...

Is there a way to make a peer dependency optional in a project?

In the process of developing module A, I have implemented a feature where users can choose to inject a Winston logger into my module. As a result, winston becomes a peer dependency. However, when attempting to include module A in another module without th ...

What is the reason for Typescript's compatibility with WScript?

Recently, I decided to install Typescript in order to get WScript intellisense in VScode. After setting it up, I was able to achieve the desired intellisense. However, I encountered an issue when compiling a Typescript file containing a WScript method usin ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

Pass information submitted through a JavaScript prompt to an expressjs endpoint

I'm currently facing a challenge in extracting the value from my prompt in order to modify a category using a JavaScript function. Typically, I would rely on a form to pass variables to the request.body, but that's not an option here. This is wh ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

A TypeScript generic function designed to accept either two arrays or two objects, but not a combination of both

Currently, I am creating an extend function in TypeScript that has the capability to: Update the first object with the keys/values of the second when given two objects. Append the elements of the second array to the first array when provided with two arr ...

When using Mongoose populate, it sometimes returns an array of objects instead of the actual data from the field

There is a query that fetches the availability array from the parking model based on the parking Id in the booking model. The query used is as follows: let startTime = await Booking.findOne( { bookingId: req.params.id }, { startTime: 1, _id: 0 ...

I'm struggling to get a specific tutorial to work for my application. Can anyone advise me on how to map a general URL to the HTTP methods of an API endpoint that is written in C

I am struggling to retrieve and display data from a C# Web API using Typescript and Angular. As someone new to Typescript, I followed a tutorial to create a service based on this guide: [https://offering.solutions/blog/articles/2016/02/01/consuming-a-rest- ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

What might be the reason why the custom markers on the HERE map are not displaying in Angular?

I'm having trouble displaying custom icons on HERE maps. Despite not receiving any errors, the icons are not showing up as expected. I have created a demo at the following link for reference: https://stackblitz.com/edit/angular-ivy-zp8fy5?file=src%2Fa ...

Is there a way to integrate TypeScript into the CDN version of Vue?

For specific areas of my project, I am utilizing the Vue CDN. I would like to incorporate Typescript support for these sections as well. However, our technical stack limitations prevent us from using Vue CLI. Is there a method to import Vue.js into a bas ...