The type 'argument with {error: null, complete: null, next: (data: Object) => void}' cannot be assigned

Having trouble with setting up web sockets. The code I have below is not compiling in TypeScript:

let observer = {
    error: null,
    complete: null,
    next: (data: Object) => {
        console.log('Message sent to websocket: ', data);
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(data));
        }
    }
};
return new AnonymousSubject<MessageEvent>(observer, observable);

The red underlined observer variable shows this message:

Argument of type '{ error: null; complete: null; next: (data: Object) => void; }' is not assignable to parameter of type 'Observer<MessageEvent<any>>'.
  Types of property 'error' are incompatible.
    Type 'null' is not assignable to type '(err: any) => void'.ts(2345)

Any suggestions on how to fix the compilation issue?

Answer №1

According to the documentation on RxJS:

interface Observer<T> {
  next: (value: T) => void
  error: (err: any) => void
  complete: () => void
}

The issue at hand is that you've set the error callback to null, which is not a valid value. It's recommended to instead log the error to the console during development:

let observer = {
  error: (err: any) => console.error(err),
  complete: () => undefined,
  next: (data: Object) => {
      console.log('Message sent to websocket: ', data);
      if (ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify(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

Updating webdriver-manager can sometimes result in a "spawn Unknown system error -86" message. This error

(Angular). webdriver-manager 12.1.7 is causing issues specifically on Intel-based Macs. When running e2e tests, the error message "spawn Unknown system error -86" is encountered. The bug has been addressed in webdriver-manager 12.1.8, however, I am facing ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Filtering multiple values from a JSON array in Angular 15, separated by commas

Currently, I am implementing Angular 15 in my project. While I am able to filter a single value from the search box, my goal is to filter multiple values separated by commas. Any assistance on achieving this would be greatly appreciated. FilterPipe impor ...

What is the reason behind TypeScript treating numbers as strings when adding them together?

Although TypeScript is strongly typed, can you explain why the code below outputs 12 instead of 3? function add_numbers(a: number, b: number){ return a + b; } var a = '1'; var b = 2; var result = add_numbers(<number><any>a, b) ...

Generating a new object from a TypeScript class using JavaScript

Currently, I am facing an issue while attempting to call a JavaScript class from TypeScript as the compiler (VS) seems to be having some trouble. The particular class in question is InfoBox, but unfortunately, I have not been able to locate a TypeScript d ...

Resetting the forms as users navigate between different tabs on the mat

I am currently working on an Angular application and I would like to incorporate mat-tabs. However, I am facing an issue where every time I switch between tabs, the inputs in each tab are resetting to empty values. Here is the HTML code snippet: <mat- ...

Insert placeholder text without access to the input field

Is it possible to activate a placeholder in a component that is outside of the current context? For example: <foreign-component [config]="someConfig" placeholder="somePlaceholder"></foreign-component> The <foreign-compo ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Tips for correctly annotating objects to address the issue of potentially being 'null'

Could use some assistance with this error: Object is possibly 'null' on this.auth.currentUser. How should I annotate this line to resolve the issue? Here's the method in question: doPasswordUpdate = (password: string): Promise<void> ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

What is the best way to implement lazy loading for child components in React's Next.js?

I am exploring the concept of lazy loading for children components in React Next JS. Below is a snippet from my layout.tsx file in Next JS: import {lazy, Suspense} from "react"; import "./globals.css"; import type { Metadata } from &quo ...

The metadata for [object Module] does not contain any ngModule information

I recently made changes to my routes by switching them from lazy loaded using a string reference to lazy loading through a call to import. However, I am facing an issue where every time I try to navigate to one of the pages, I encounter the following erro ...

Error: PrimeNG Treenode Component is having difficulty rendering the data

I'm currently working on a project in Angular 5 where I need to display data in a Treenode format. The data is coming from a service and is structured as follows (in object form): { "data": [ { "label": "Documents", ...

What is the best way to add prefixes to my SCSS style sheets?

After attempting to add prefixes to my scss files, I came across the autoprefixer tool. However, I discovered that it only supports CSS files. Is there a way to utilize autoprefixer with scss files? Here are the commands for Autoprefixer: npm install post ...

Transformation of Python code into Blockly blocks

As the founder of edublocks.org, I am interested in adding Python to Blocks functionality on the platform. At the moment, users can only transition from Blocks to Python. Is there anyone who has experience with this and can provide guidance on how to achi ...

Encountering an error with dynamic routing in Angular 4 when using dynamic components

Upon receiving routing configuration from a server and loading it before the application bootstrap, the config.json file contains the following setup: [{ "path": "dashboard", "component": "SingleComponent", "data": {...} }, { "path": "payment", ...

Ways to manage an interactive pricing structure chart in Angular?

In my application, users can choose from four different types of plans that are retrieved from the backend. Once a plan is selected, they are directed to a payment page. The pricing table page can be revisited, and if a user has already purchased a plan, t ...

Utilizing Mongoose RefPath in NestJS to execute populate() operation

After registering my Schema with mongoose using Dynamic ref, I followed the documentation available at: https://mongoosejs.com/docs/populate.html#dynamic-ref @Schema({ collection: 'quotations' }) export class QuotationEntity { @Prop({ r ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

Adding Dynamic Checkboxes to Angular Forms in Angular 4

Currently, I am in the process of working on an angular 4 form using Angular forms. I am looking for a way to dynamically add an input (checkbox) to the formArray after constructing the form. Here is the TypeScript code snippet: signes_p = [ { id: &apo ...