Issue with typing in subscription encountered in Typescript RXjs version 6.6.0

Have you attempted using the code snippet below?

   const data = new Data()

    data.subscribe({
        next: (value) => {},
        error: (value) => {},
        complete: (value) => {},
    });

Encountering this error:

Compilation failed.

src/app/services/data/data-bank-service/data-bank.service.ts:40:57 - error TS2554: Expected 2-3 arguments, received only 1.

40
data.subscribe({ ~~~~~~~~~~~ 41 next: (value) => {}, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ... 43 complete: (value) => {}, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 44 }); ~~~~~~~~~~

node_modules/rxjs/internal/Observable.d.ts:51:39 51 subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription; ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'Error' parameter missing from the argument list.

I understand that there is a new syntax for passing callbacks

Changing from

subscribe(callback, callback ,callback)
to
subscribe({next: callback, error: callback, complete: callback})

but I am having trouble implementing it correctly. Any insights?

Referenced website example

http://reactivex.io/rxjs/manual/overview.html#subject

Answer №1

According to a comment by martin on Stack Overflow, the issue with typescript rxjs version 6.6.0 subscription lies in using the incorrect type for complete. Instead of (value: unknown) => void, it should be () => void.

I would like to delve into why this error is displayed as it is.

The problematic method, subscribe, in RxJS has multiple signature overloads as found in its codebase here.

  subscribe(observer?: PartialObserver<T>): Subscription;
  /** @deprecated Use an observer instead of a complete callback */
  subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;
  /** @deprecated Use an observer instead of an error callback */
  subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
  /** @deprecated Use an observer instead of a complete callback */
  subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;
  subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;

When calling this method, TypeScript evaluates the overloads sequentially from top to bottom.

The object passed by OP was

{
  next: (value) => {},
  error: (value) => {},
  complete: (value) => {},
}

Initially, the inferred signatures were

{
  next: (value: unknown) => void,
  error: (value: unknown) => void,
  complete: (value: unknown) => void,
}

Type inference occurs only when the correct overload is determined based on argument compatibility in the subscribe method.

As TypeScript matches the first signature, it expects a PartialObserver object which must include at least one of next, error, or complete properties. The provided object did not fit due to the wrong type for complete.

This mismatch could lead to silent errors in some TypeScript versions, causing confusion. Subsequent mismatches in other signatures may also occur depending on the version used.

In a similar example run on TS version 4.2.3, the error message is more detailed, showing clearer information compared to what the OP encountered with TS2554:

No overload matches this call.
  Overload 1 of 5, '(observer?: PartialObserver<unknown> | undefined): Subscription', gave the following error.
    Type '(value: any) => void' is not assignable to type '() => void'.
  Overload 2 of 5, '(next?: ((value: unknown) => void) | undefined, error?: ((error: any) => void) | undefined, complete?: (() => void) | undefined): Subscription', gave the following error.
    Argument of type '{ next: (value: unknown) => void; error: (value: any) => void; complete: (value: any) => void; }' is not assignable to parameter of type '(value: unknown) => void'.
      Object literal may only specify known properties, and 'next' does not exist in type '(value: unknown) => void'.

To avoid such confusing errors, it's important to understand and evaluate all possible overloads while troubleshooting.

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

Challenge with Angular date selection component

I am currently utilizing ngbdatepicker in my form. I want to save the date separately and retrieve it as shown below. <input class="form-control ngbfield custom-form-control" required [ngClass]="{'is-invalid':f.touched && birthDay.inv ...

Update constant data returned from Angular2 service

Issue at Hand: I am facing an issue where I want to store default data in a separate file so that I can easily reset the default value when needed. However, the Const Data seems to be getting updated. I could simply hardcode the value directly into the co ...

Bars of varying heights (Google Chart)

I have incorporated a Google chart within a mat-grid-tile. In this setup, one column displays a value of 50, while the other showcases a value of 30. These particular values are sourced from myService and are accurate. Although when I hover over the bars i ...

After ngAfterViewInit, the @ViewChild element has not been defined

@ViewChild('videoPlayer') myVidElement: ElementRef; There is an HTML5 video element in the markup with the ViewChild specified as above However, I am facing an issue where the element is not accessible and is logged as undefined in both ngOnIni ...

How can I utilize Luxon to calculate the total number of days that are equal to or greater than 30?

Looking at my current array structure const arr = [ { id: '1', name: 'thing1', createdAt: '2022-09-21T16:26:02Z', }, { id: '2', name: 'thing1', createdAt: '2022-11-21T16:20:20Z', } ...

There will be no further upgrades available for Angular CLI after version 1.6.0

Based on the latest information from npm, the current version of @angular/cli is v6.2.5. Upon running ng -v, the output shows: _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ &b ...

Selecting options in combobox for each row in a table using Angular 2 programmatically

I am currently working on an Angular 2 application using TypeScript. In one of the tables within the application, there is a select control in one of the columns. The contents of this select control are bound to another string array. <table ngContr ...

If you're not utilizing v-model.lazy, Vue3 Cleave js may encounter functionality issues

I am currently experimenting with cleavejs to format the thousand separator in my input numbers. I've noticed a strange behavior where if I input 1000.123, it displays as 1,000.12 which is the correct format. However, the v-model value remains as 1000 ...

Slim 4 with Angular 10: Issues with downloading PDF files through API, as Angular blob response is coming back empty

Struggling to integrate the download PDF Angular API with Slim 4 API. The response from Slim can be seen in the browser network, but when trying to parse it in Angular, it comes back empty. All the necessary headers have been added on both Angular and Slim ...

Navigating through elements in Angular

I am working with multiple Angular components housed within a display:flex div container. I am fetching datatable from an API, and it contains the same number of rows as there are components. Each row in the datatable corresponds to data for each compone ...

Add an image to a directory with Angular 7

I am having trouble uploading an Image to the assets/ folder using Angular 7. Below is my attempted solution: HTML: <form [formGroup]="form" (ngSubmit)="postData()" class="intro-form-css"> <div class="form-row"> ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

What is the best way to display a scrollbar at the bottom of the table while setting the table height to

After writing the css provided below, I noticed that it works fine on my laptop screen. However, when viewing it on a larger monitor, there is empty space at the end of the table. .wrapper{ width:auto; height: 500px; overflow-x: scroll; ...

Steps for hosting Angular on Firebase:1. Set up a Firebase project

I am having trouble getting my Angular app to display properly on Firebase after deployment. Instead of showing my app, it is displaying the default index.html generated by Firebase. How can I fix this? This is what my firebase.json file looks like: { ...

Instead of being viewed in the browser, the CSV file is being downloaded

I'm currently using Jhipster and have a function generated by Jhipster to open files in the browser. However, I'm facing an issue with this function when it comes to opening CSV files - instead of opening in the browser, they are being downloaded ...

I'm attempting to conduct unit testing in my code using jest, but I keep encountering an error

I am currently testing unit testing in my code wherein a function takes two parameters and the goal is to check if the function is functioning properly. As a beginner in using jest, I am still learning how to write effective test cases. import React, { F ...

Storing data retrieved from MongoDB into a local array in a MEAN stack

I am currently working on a small application using the MEAN stack. I have saved some user details in MongoDB and now I want to retrieve and store only the email ids in a local array. The fetching part is working well, but I'm facing issues with savin ...

Script execution in '<URL>' has been prevented due to sandboxing of the document's frame and the absence of the 'allow-scripts' permission setting

When I deploy my pure Angular application with a REST API to a production server and try to access its URL from another site (such as a link in an email), I encounter a strange problem. Firefox doesn't provide any error message, but Chrome says: Blo ...

Clarity 3 enhancement: Encounter of NullInjectorError with TreeFocusManagerService

Upon updating my project to Angular9/Clarity3 from Angular8/Clarity2, I encountered some issues while navigating the app. I was able to fix some problems, but now I'm facing a NullInjectorError: ERROR Error: Uncaught (in promise): NullInjectorErr ...

The function Interceptor.intercept is not defined

For a while now, I've been working on implementing an application-wide interceptor. However, no matter what I do, I keep encountering the same frustrating error: TypeError: this.interceptor.intercept is not a function After countless hours of debugg ...