How to type get error response data from axios AsyncThunk

I am having a hard time access the error response data, The code worked on javascript I moved to typescript now things are confusing. Currently i get ‘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 tried

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

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

Anyone has a proper solution for this
Thank you very much

Leave a Comment