"Troubleshooting Typecscript and Angular: Dealing with mismatched argument

How can I resolve this Angular error:

(response: HttpResponse<User>) => {

which results in the following error message:

Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(value: HttpResponse<User> | HttpErrorResponse) => void'.
  Types of parameters 'response' and 'value' are incompatible.
    Type 'HttpResponse<User> | HttpErrorResponse' is not assignable to type 'HttpResponse<User>'.
      Type 'HttpErrorResponse' is missing the following properties from type 'HttpResponse<User>': body, clone

ALSO

(response.body); raises the following error:

Argument of type 'User | null' is not assignable to parameter of type 'User'.
  Type 'null' is not assignable to type 'User'.

I am currently using TypeScript 4.5.5 in my Angular project.

The function causing the issue is:

public onLogin(user: User): void{
    console.log(user)
    this.subscriptions.push(
      this.authenticationService.login(user).subscribe(
        (response: HttpResponse<User>) => {
          const token: string = response.headers.get(HeaderType.JWT_TOKEN) || '';
          this.authenticationService.saveToken(token);
          this.authenticationService.addUserToLocalCache(response.body);
          this.router.navigateByUrl('/dashboard');
        },
        (error: HttpErrorResponse) => {
          console.log(error);
          this.sendErrorNotification(NotificationType.ERROR, error.error.message);
        }
      )
    );
  }

NOTE: This function worked without issues in a previous project with a different version of TypeScript.

Answer №1

Issue 1

My observation regarding the login function in the AuthenticationService is that you are returning

Observable<HttpResponse<User> | HttpErrorResponse>
, as shown in the code snippet below:

login(user: User) {
  return (
    this.httpClient
      .post<HttpResponse<User>>(/* Login API url */, user)
      .pipe(catchError((err) => this.handleError(err)))
  );
}

handleError(err: HttpErrorResponse) {
  return of(err);
}

Solution for Issue 1

In order to properly handle and return errors within an Observable for subsequent subscriptions, it is recommended to use (rxjs) throwError:

import { throwError } from 'rxjs';

login(user: User) {
  return (
    this.httpClient
      .post<HttpResponse<User>>(/* Login API url */, user)
      .pipe(catchError((err) => this.handleAndThrowError(err)))
  );
}

handleAndThrowError(err: HttpErrorResponse) {
  return throwError(err);
}

Issue 2

Regarding HttpResponse<T>,

class HttpResponse<T> extends HttpResponseBase {
  constructor(init: { body?: T; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {})
  body: T | null

  ...
}

The value of response.body can potentially be null.


Solution for Issue 2

To handle the possibility of null for response.body, you can include a null check like so:

if (response.body)
  this.authenticationService.addUserToLocalCache(response.body);

Check out a Sample Demo on StackBlitz (featuring multiple scenarios)

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

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Changing the default font size has no effect on ChartJS

I'm trying to customize the font size for a chart by changing the default value from 40px to 14px. However, when I set Chart.defaults.global.defaultFontSize to 14, the changes don't seem to take effect. Below is the code snippet for reference. An ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

Changes are made to the Angular template-driven form after certain controls have been added or removed

Within a fieldset, there exists a flexible number of 'select' drop down lists, accompanied by a button after each one (except the last one) to remove it. Upon selecting an option from the last select control, a new select control is dynamically a ...

Incorporating a skeletal design effect into a table featuring sorting and pagination options

Is there a way to implement the Skeleton effect in a MUI table that only requires sorting and pagination functionalities? I tried using the 'loading' hook with fake data fetching and a 3-second delay, but it doesn't seem to work with DataGri ...

Exploring Angular's AG Grid ToolTips

I am encountering an issue while trying to implement AG Grids ToolTip functionality. Following the example provided at https://www.ag-grid.com/documentation/angular/component-tooltip/#example-custom-tooltip-component, I attempted to import { ITooltipAngula ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

Relocating the node_modules folder results in syntax errors arising

I encountered a perplexing syntax error issue. I noticed that having a node_modules directory in the same location I run npm run tsc resolves the issue with no syntax errors. However, after relocating the node_modules directory to my home directory, ~ , a ...

Angular 4: Issue with sending POST data via HTTP requests

I am currently working on developing a Web Application and I am facing an issue with testing the HTTP functions. Here is an example of my code snippet: import { Injectable } from '@angular/core'; import { Headers, RequestOptions, Http } from & ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Using Angular2 moment to format a date in a specific way

Encountered an error while using the amTimeAgo pipe from angular2-moment. The error message is as follows: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not ...

Jest does not support the processing of import statements in typescript

I am attempting to execute a simple test. The source code is located in src/index.ts and contains the following: const sum = (a, b) => {return a+b} export default sum The test file is located in tests/index.test.ts with this code: impor ...

Restrict the object field type to an array by analyzing control-flow for accessing elements within brackets

Enhancements in type narrowing using control-flow analysis for bracket element access have been introduced in TypeScript 4.7. One thing I'd like to do is verify if the accessed field is an array or not. Currently, the type guard seems to be ineffecti ...

Why is the AngularJS 2 child @Component not being replaced in this scenario?

UPDATE: It seems that the issue lies in how I am structuring and serving the project rather than a coding problem. If I find a solution, I'll be sure to update this post. Thank you for your assistance. I'm currently developing an AngularJS 2 ap ...

How can I use Laravel to enter data using the post method?

I've been struggling with data transfer in my Angular component for a while now, specifically using a post method. Despite extensive research and reading various documents, I haven't been able to find a solution. Can you assist me with this issue ...

Live reload feature in Angular/Ionic app fails to update the app while running on Android Studio emulator

When running "ionic capacitor run android" in my Mac terminal, I can manually click the play button in Android Studio to view the application with its updated code changes. On the other hand, if I use "ionic capacitor run android -l" in my Mac terminal, t ...

I am currently struggling with a Typescript issue that I have consulted with several individuals about. While many have found a solution by upgrading their version, unfortunately, it

Error message located in D:/.../../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts TypeScript error in D:/.../.../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts(1,13): Expecting '=', TS1005 1 | import type { Reducer, ReducersMapO ...

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

Setting the background color of a button within a template in an Angular 8 component using style.background

I have been exploring the different versions of Angular and their changes. Currently, I am enrolled in an Angular course on Udemy where I have installed Angular 8. In the course, it is mentioned to use style.backgroundColor on a button inside the template ...